
package com.huaweicloud.saaslanding.install.applicationservice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huaweicloud.saaslanding.basic.database.mybatis.conditions.query.QueryWrap;
import com.huaweicloud.saaslanding.basic.enumeration.AppTypeEnum;
import com.huaweicloud.saaslanding.basic.enumeration.ComponentLabelEnum;
import com.huaweicloud.saaslanding.basic.enumeration.DataSourceTypeEnum;
import com.huaweicloud.saaslanding.basic.enumeration.DbMultiTenantMode;
import com.huaweicloud.saaslanding.basic.enumeration.IdaasEnum;
import com.huaweicloud.saaslanding.basic.enumeration.MonoDeploymentInfoBelongEnum;
import com.huaweicloud.saaslanding.basic.enumeration.RoleCodeEnum;
import com.huaweicloud.saaslanding.basic.enumeration.SSLCloudServiceEnum;
import com.huaweicloud.saaslanding.basic.enumeration.SecurityGroupBelongEnum;
import com.huaweicloud.saaslanding.basic.enumeration.ServiceManageFrameTypeEnum;
import com.huaweicloud.saaslanding.basic.enumeration.SubnetBelongEnum;
import com.huaweicloud.saaslanding.basic.enumeration.VpcBelongEnum;
import com.huaweicloud.saaslanding.basic.enumeration.combo.PackageTypeEnum;
import com.huaweicloud.saaslanding.basic.enumeration.deployment.AppMultiTenantMode;
import com.huaweicloud.saaslanding.basic.enumeration.deployment.ManageDeployStrategyEnum;
import com.huaweicloud.saaslanding.basic.enumeration.deployment.ProbeType;
import com.huaweicloud.saaslanding.basic.enumeration.worksheet.AuthorityPolicyEnum;
import com.huaweicloud.saaslanding.basic.enumeration.worksheet.PolicyStatementEnum;
import com.huaweicloud.saaslanding.basic.exception.BizException;
import com.huaweicloud.saaslanding.basic.exception.code.ExceptionCode;
import com.huaweicloud.saaslanding.basic.routelink.constant.RouteLinkConstant;
import com.huaweicloud.saaslanding.basic.uid.UidGenerator;
import com.huaweicloud.saaslanding.basic.utils.BeanPlusUtil;
import com.huaweicloud.saaslanding.basic.utils.EncryptionUtil;
import com.huaweicloud.saaslanding.basic.utils.RegexUtil;
import com.huaweicloud.saaslanding.basic.utils.ResourceNamingUtil;
import com.huaweicloud.saaslanding.dao.common.entity.app.AppComponent;
import com.huaweicloud.saaslanding.dao.common.entity.app.AppDeployment;
import com.huaweicloud.saaslanding.dao.common.entity.app.AppImage;
import com.huaweicloud.saaslanding.dao.common.entity.app.AppPackage;
import com.huaweicloud.saaslanding.dao.common.entity.app.AppPackageResource;
import com.huaweicloud.saaslanding.dao.common.entity.app.AppResource;
import com.huaweicloud.saaslanding.dao.common.entity.app.AppRole;
import com.huaweicloud.saaslanding.dao.common.entity.app.AppRoleResource;
import com.huaweicloud.saaslanding.dao.common.entity.app.AppTemplate;
import com.huaweicloud.saaslanding.dao.common.entity.app.CheckHealth;
import com.huaweicloud.saaslanding.dao.common.entity.app.MonoAppDeployment;
import com.huaweicloud.saaslanding.dao.common.entity.app.MonoAppLicenseModule;
import com.huaweicloud.saaslanding.dao.common.entity.app.MonoAppPackageEcsSpec;
import com.huaweicloud.saaslanding.dao.common.entity.app.PackageModule;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.CceInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.CseInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.ElbInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.EmailInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.EndpointInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.GaussDBInstanceInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.IamAccountInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.KeycloakInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.LtsInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.ObsInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.RdsInstanceInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.RdsResource;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.RedisInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.SkywalkingInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.SmsInfo;
import com.huaweicloud.saaslanding.dao.common.entity.cloudservice.VpcInfo;
import com.huaweicloud.saaslanding.dao.common.entity.integrated.ImcParams;
import com.huaweicloud.saaslanding.dao.common.entity.master.Resources;
import com.huaweicloud.saaslanding.dao.common.entity.master.Role;
import com.huaweicloud.saaslanding.dao.common.entity.master.RoleResources;
import com.huaweicloud.saaslanding.dao.common.entity.master.User;
import com.huaweicloud.saaslanding.dao.common.entity.security.CertStoreInfo;
import com.huaweicloud.saaslanding.dao.common.entity.security.CloudServiceSslStrategy;
import com.huaweicloud.saaslanding.dao.common.entity.security.SecurityGroup;
import com.huaweicloud.saaslanding.dao.common.entity.security.Subnet;
import com.huaweicloud.saaslanding.dao.common.entity.security.WorkSecretKey;
import com.huaweicloud.saaslanding.dao.common.entity.tenant.SubscribedApp;
import com.huaweicloud.saaslanding.dao.common.entity.tenant.TenantAppDomain;
import com.huaweicloud.saaslanding.dao.common.entity.upgrade.ComponentRelationship;
import com.huaweicloud.saaslanding.dao.common.entity.upgrade.RouteLink;
import com.huaweicloud.saaslanding.dao.common.entity.worksheet.AuthorityPolicy;
import com.huaweicloud.saaslanding.dao.common.entity.worksheet.PolicyStatement;
import com.huaweicloud.saaslanding.dao.common.entity.worksheet.WorksheetUser;
import com.huaweicloud.saaslanding.dao.common.entity.worksheet.WorksheetUserGroup;
import com.huaweicloud.saaslanding.dao.common.repository.app.AppDeploymentBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.app.AppImageBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.app.AppPackageBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.app.AppPackageResourceBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.app.AppResourceBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.app.AppRoleBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.app.AppRoleResourceBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.app.AppTemplateBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.app.CheckHealthBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.app.MonoAppDeploymentBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.app.MonoAppLicenseModuleBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.app.MonoAppPackageEcsSpecBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.app.PackageModuleBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.CceInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.CseInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.ElbInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.EmailBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.EndpointInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.GaussDBInstanceInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.IamAccountInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.KeycloakInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.LtsInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.ObsInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.RdsInstanceInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.RdsResourceBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.RedisInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.SkywalkingInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.SmsBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.cloudservice.VpcInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.integrated.ImcParamsBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.master.ResourceBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.master.RoleBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.master.RoleResourceBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.master.UserBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.security.CertStoreInfoBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.security.CloudServiceSslStrategyBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.security.SecurityGroupBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.security.SubnetBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.security.WorkSecretKeyBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.tenant.SubscribedAppBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.tenant.TenantAppDomainBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.upgrade.RouteLinkBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.worksheet.AuthorityPolicyBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.worksheet.PolicyStatementBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.worksheet.WorksheetUserBaseMapper;
import com.huaweicloud.saaslanding.dao.common.repository.worksheet.WorksheetUserGroupBaseMapper;
import com.huaweicloud.saaslanding.huawei.cce.constant.CceUrlConstant;
import com.huaweicloud.saaslanding.install.applicationservice.RdsService;
import com.huaweicloud.saaslanding.install.dto.OneAccessAppDto;
import com.huaweicloud.saaslanding.install.enumeration.AppNameEnum;
import com.huaweicloud.saaslanding.install.properties.Cce;
import com.huaweicloud.saaslanding.install.properties.Cse;
import com.huaweicloud.saaslanding.install.properties.DatabaseConfig;
import com.huaweicloud.saaslanding.install.properties.Dcs;
import com.huaweicloud.saaslanding.install.properties.EcsSpecification;
import com.huaweicloud.saaslanding.install.properties.Elb;
import com.huaweicloud.saaslanding.install.properties.Email;
import com.huaweicloud.saaslanding.install.properties.Endpoint;
import com.huaweicloud.saaslanding.install.properties.Iam;
import com.huaweicloud.saaslanding.install.properties.Idaas;
import com.huaweicloud.saaslanding.install.properties.Lts;
import com.huaweicloud.saaslanding.install.properties.Nacos;
import com.huaweicloud.saaslanding.install.properties.Obs;
import com.huaweicloud.saaslanding.install.properties.Skywalking;
import com.huaweicloud.saaslanding.install.properties.Sms;
import com.huaweicloud.saaslanding.install.properties.Ssl;
import com.huaweicloud.saaslanding.install.properties.SslStrategy;
import com.huaweicloud.saaslanding.install.properties.Swr;
import com.huaweicloud.saaslanding.install.properties.UpgradeSwr;
import com.huaweicloud.saaslanding.install.properties.Vpc;
import com.huaweicloud.saaslanding.install.repository.ComponentInfoMapper;
import com.huaweicloud.saaslanding.install.repository.DataRepository;
import com.huaweicloud.saaslanding.install.repository.QuartzRepository;
import com.huaweicloud.saaslanding.install.repository.RdsRepository;
import com.huaweicloud.saaslanding.install.repository.TenantAppMapper;
import com.huaweicloud.saaslanding.install.util.DomainNameUtil;

import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 功能描述
 *
 * @since 2022-03-24
 */
@Slf4j
@Component
public class RdsServiceImpl implements RdsService {

    @Value("${spring.datasource.druid.driver-class-name}")
    private String dbDriver;

    @Value("${saaslanding-install.config-discovery-frame.type}")
    private String configDiscoveryFrame;

    @Resource
    private Dcs dcs;

    @Resource
    private RedisInfoBaseMapper redisInfoBaseMapper;

    @Resource
    private SubscribedAppBaseMapper subscribedAppBaseMapper;

    @Resource
    private Endpoint endpoint;

    @Resource
    private RdsRepository rdsRepository;

    @Resource
    private QuartzRepository quartzRepository;

    @Resource
    private DataRepository dataRepository;

    @Resource
    private WorkSecretKeyBaseMapper workSecretKeyBaseMapper;

    @Resource
    private AppTemplateBaseMapper appTemplateBaseMapper;

    @Resource
    private AppPackageBaseMapper appPackageBaseMapper;

    @Resource
    private ImcParamsBaseMapper imcParamsBaseMapper;

    @Resource
    private EndpointInfoBaseMapper endpointInfoBaseMapper;

    @Resource
    private CseInfoBaseMapper cseInfoBaseMapper;

    @Resource
    private AppImageBaseMapper appImageBaseMapper;

    @Resource
    private IamAccountInfoBaseMapper iamAccountInfoBaseMapper;

    @Resource
    private RdsResourceBaseMapper rdsResourceBaseMapper;

    @Resource
    private ComponentInfoMapper componentInfoMapper;

    @Resource
    private AppDeploymentBaseMapper appDeploymentBaseMapper;

    @Resource
    private RoleBaseMapper roleBaseMapper;

    @Resource
    private RoleResourceBaseMapper roleResourceBaseMapper;

    @Resource
    private CceInfoBaseMapper cceInfoBaseMapper;

    @Resource
    private ElbInfoBaseMapper elbInfoBaseMapper;

    @Resource
    private ObsInfoBaseMapper obsInfoBaseMapper;

    @Resource
    private UserBaseMapper userBaseMapper;

    @Resource
    private WorksheetUserBaseMapper worksheetUserBaseMapper;

    @Resource
    private AuthorityPolicyBaseMapper authorityPolicyBaseMapper;

    @Resource
    private PolicyStatementBaseMapper policyStatementBaseMapper;

    @Resource
    private WorksheetUserGroupBaseMapper worksheetUserGroupBaseMapper;

    @Resource
    private Iam iam;

    @Resource
    private Cce cce;

    @Resource
    private Elb elb;

    @Resource
    private EcsSpecification ecsSpecification;

    @Resource
    private Cse cse;

    @Resource
    private Swr swr;

    @Resource
    private Obs obs;

    @Resource
    private Ssl ssl;

    @Resource
    private Vpc vpc;

    @Resource
    private Skywalking skywalking;

    @Resource
    private UpgradeSwr upgradeSwr;

    @Resource
    private Idaas idaas;

    @Resource
    private AppRoleBaseMapper appRoleRepository;

    @Resource
    private AppRoleResourceBaseMapper appRoleResourceRepository;

    @Resource
    private Lts lts;

    @Resource
    private LtsInfoBaseMapper ltsInfoRepository;

    @Resource
    private CertStoreInfoBaseMapper certStoreInfoBaseMapper;

    @Resource
    private UidGenerator uidGenerator;

    @Resource
    private MonoAppDeploymentBaseMapper monoAppDeploymentBaseMapper;

    @Resource
    private VpcInfoBaseMapper vpcInfoBaseMapper;

    @Resource
    private SubnetBaseMapper subnetBaseMapper;

    @Resource
    private SecurityGroupBaseMapper securityGroupBaseMapper;

    @Resource
    private MonoAppLicenseModuleBaseMapper monoAppLicenseModuleBaseMapper;

    @Resource
    private PackageModuleBaseMapper packageModuleBaseMapper;

    @Resource
    private MonoAppPackageEcsSpecBaseMapper monoAppPackageEcsSpecBaseMapper;

    @Resource
    private SslStrategy sslStrategy;

    @Resource
    private CloudServiceSslStrategyBaseMapper cloudServiceSslStrategyBaseMapper;

    @Resource
    private SkywalkingInfoBaseMapper skywalkingInfoBaseMapper;

    @Resource
    private Nacos nacos;

    @Resource
    private KeycloakInfoBaseMapper keycloakInfoBaseMapper;

    @Resource
    private RouteLinkBaseMapper routeLinkBaseMapper;

    @Resource
    private ResourceBaseMapper resourceBaseMapper;

    @Resource
    private AppResourceBaseMapper appResourceBaseMapper;

    @Resource
    private AppRoleBaseMapper appRoleBaseMapper;

    @Resource
    private AppRoleResourceBaseMapper appRoleResourceBaseMapper;

    @Resource
    private AppPackageResourceBaseMapper appPackageResourceBaseMapper;

    @Resource
    private TenantAppMapper tenantAppMapper;

    @Resource
    private DatabaseConfig databaseConfig;

    @Resource
    private RdsInstanceInfoBaseMapper rdsInstanceInfoBaseMapper;

    @Resource
    private GaussDBInstanceInfoBaseMapper gaussDBInstanceInfoBaseMapper;

    // 平台侧口令，初始化salt表之前生成
    private String saasPwd = null;

    @Autowired
    private Sms sms;

    @Autowired
    private Email email;

    @Autowired
    private SmsBaseMapper smsBaseMapper;

    @Autowired
    private EmailBaseMapper emailBaseMapper;

    @Resource
    private TenantAppDomainBaseMapper tenantAppDomainBaseMapper;

    @Autowired
    private CheckHealthBaseMapper checkHealthBaseMapper;

    @Override
    public void initDataBase() {
        log.info("========== start: 初始化数据库 ==========");

        String database = databaseConfig.getConnectionInfo().getDbName();

        String prefixCode = ResourceNamingUtil.getPrefixCode();

        RegexUtil.checkPrefixCode(prefixCode);

        // 创建数据库表
        rdsRepository.createTable(database, prefixCode);

        // 创建数据库表(续)
        rdsRepository.createTableContinue(database, prefixCode);

        // 创建quartz相关表
        quartzRepository.createQrtzDatabase(database);

        // 判断能否进行数据库初始化，依据是平台侧应用模板表是否存在控制台应用的数据
        if (canInit()) {
            // 初始化 口令表（hsl_salt），返回平台侧口令
            initSalt();

            // 初始化keycloak Info 表
            initKeycloakInfo();

            // 初始化 skywalking信息表（hsl_skywalking_info）
            tryInitSkywalking();

            // 初始化 redis信息表（hsl_redis_info）
            initRedis();

            // 初始化 IMC配置参数表（hsl_imc_params）
            initImcParams(saasPwd);

            // 初始化 EndPoint信息表（hsl_endpoint_info）
            initEndpointInfo();

            // 初始化 应用模板表（hsl_app_template）
            List<Long> appIdList = initAppTemplate(saasPwd);

            // 初始化 业务应用API表
            initAppServiceApi(appIdList);

            // 初始化 业务应用功能表
            initAppFunctions(appIdList);

            // 初始化订阅应用表
            initHslSubscribedApp(appIdList.get(0));
            long subAppId = getSubscribedAppId();

            // 初始化 角色表（hsl_role）+ 资源表（hsl_resource）+ 角色资源关系表（hsl_role_resource）
            initAppRoleResource(appIdList, subAppId);

            // 初始化 套餐表（hsl_package_info）
            initAppPackageResource(appIdList);

            // 初始化 组件表（hsl_component_info）
            initAppComponent(appIdList);

            // 初始化 健康检查表(hsl_check_health)
            initCheckHealth(appIdList);

            // 初始化 组件上下游表（hsl_component_relationship）
            initComponentRelationship();

            // 初始化 镜像表（hsl_image）
            initImage(appIdList);

            // 初始化升级镜像信息
            initUpgradeImage(appIdList);

            // 初始化 部署信息表（hsl_deployment_info）
            initDeploymentInfo(appIdList, saasPwd);

            // 初始化 单体应用信息
            initMonoAppData(saasPwd);

            // 初始化 LTS信息表（hsl_lts_info）
            tryInitLtsInfo();

            // 初始化 证书信息表（hsl_store_info）
            tryInitCertStoreInfo(saasPwd);

            // 初始化标签表
            insertLabel();

            // 初始化云服务SSL认证策略相关表数据
            initCloudServiceSslStrategy();

            // 初始化路由链路表
            initRouteLink();

            initSmsAndEmailInfo(saasPwd);

            // 初始化租户应用域名表
            initTenantAppDomain();

            log.info("========== end: 初始化数据库 ==========");
        } else {
            // APP 已存在相应记录，请勿重复install
            log.error("APP 已存在相应记录，请勿重复install");
            throw new BizException(ExceptionCode.APP_REPEATE_INSTALL.getCode(),
                ExceptionCode.APP_REPEATE_INSTALL.getMsg());
        }
    }

    private void initCheckHealth(List<Long> appIdList) {
        QueryWrapper<AppComponent> appComponentQueryWrapper = new QueryWrapper<>();
        appComponentQueryWrapper.lambda().eq(AppComponent::getIsDel, false).in(AppComponent::getAppId, appIdList);
        List<AppComponent> appComponents = componentInfoMapper.selectList(appComponentQueryWrapper);

        List<CheckHealth> checkHealthList = new ArrayList<>();
        appComponents.stream()
            .filter(appComponent -> !ComponentLabelEnum.B_UI.getLabel().equals(appComponent.getLabel()))
            .forEach(appComponent -> {
                CheckHealth survivalCheckHealth = new CheckHealth();
                CheckHealth readyCheckHealth = new CheckHealth();
                String survivalPath = appComponent.getContextPath().concat(CceUrlConstant.SURVIVAL_CHECK_HEALTH_PATH);
                String readyPath = appComponent.getContextPath().concat(CceUrlConstant.READY_CHECK_HEALTH_PATH);
                survivalCheckHealth.setProbeType(ProbeType.SURVIVAL.getCode())
                    .setComponentId(appComponent.getId())
                    .setTimeoutSeconds(1L)
                    .setInitialDelaySeconds(0L)
                    .setPeriodSeconds(20L)
                    .setSuccessThreshold(1)
                    .setFailureThreshold(10)
                    .setScheme(1)
                    .setPath(survivalPath)
                    .setPort(appComponent.getPort().toString());
                readyCheckHealth.setProbeType(ProbeType.READY.getCode())
                    .setComponentId(appComponent.getId())
                    .setTimeoutSeconds(1L)
                    .setInitialDelaySeconds(0L)
                    .setPeriodSeconds(20L)
                    .setSuccessThreshold(1)
                    .setFailureThreshold(10)
                    .setScheme(1)
                    .setPath(readyPath)
                    .setPort(appComponent.getPort().toString());

                checkHealthList.add(survivalCheckHealth);
                checkHealthList.add(readyCheckHealth);
            });
        checkHealthBaseMapper.insertBatchSomeColumn(checkHealthList);
    }

    private void initSmsAndEmailInfo(String saasPwd) {
        List<SmsInfo> smsInfos = new ArrayList<>();
        sms.getNotificationEvents().forEach((event, config) -> {
            String appSecret = EncryptionUtil.encrypt(saasPwd, sms.getAppSecret());
            SmsInfo smsInfo = new SmsInfo().setProxy(sms.getProxy())
                .setProxyPort(sms.getProxyPort())
                .setUrl(sms.getUrl())
                .setAppKey(sms.getAppKey())
                .setAppSecret(appSecret)
                .setSender(sms.getSender())
                .setMinInterval(sms.getMinInterval())
                .setMaxRequestPerDay(sms.getMaxRequestPerDay())
                .setEvent(event.toString())
                .setTemplateId(config.getTemplateId())
                .setSignature(config.getSignature());
            smsInfos.add(smsInfo);
        });
        smsBaseMapper.insertBatchSomeColumn(smsInfos);
        List<EmailInfo> emailInfos = new ArrayList<>();
        email.getNotificationEvents().forEach((event, config) -> {
            String password = EncryptionUtil.encrypt(saasPwd, email.getPassword());
            EmailInfo emailInfo = new EmailInfo();
            emailInfo.setHost(email.getHost())
                .setUsername(email.getUsername())
                .setPassword(password)
                .setSenderEmail(email.getSenderEmail())
                .setSenderName(email.getSenderName())
                .setMinInterval(email.getMinInterval())
                .setMaxRequestPerDay(email.getMaxRequestPerDay())
                .setEvent(event.toString())
                .setSubject(config.getSubject())
                .setBody(config.getBody());
            emailInfos.add(emailInfo);
        });
        emailBaseMapper.insertBatchSomeColumn(emailInfos);
    }

    private void initTenantAppDomain() {
        AppTemplate saasAppInfo = appTemplateBaseMapper.getSaasAppInfo();
        TenantAppDomain tenantAppDomain = new TenantAppDomain();
        String domainName = DomainNameUtil.getDomainName();
        String contextPath = componentInfoMapper.selectBUIContextPathByAppId(saasAppInfo.getId());
        String hostRecord = ResourceNamingUtil.builderTenantAppDomainName(domainName, contextPath);
        tenantAppDomain.setAppId(saasAppInfo.getId())
            .setTenantCode(databaseConfig.getConnectionInfo().getDbName())
            .setHostRecord(hostRecord)
            .setIsTemporary(false)
            .setIp(elb.getElbIp());

        tenantAppDomainBaseMapper.insert(tenantAppDomain);
    }

    /**
     * 初始化工单授权策略和内置用户组表
     */
    @Override
    public void initWorksheet() {
        Map<Integer, AuthorityPolicy> codeToPolicy = new HashMap<>();
        for (AuthorityPolicyEnum policyEnum : AuthorityPolicyEnum.values()) {
            AuthorityPolicy authorityPolicy = new AuthorityPolicy().setName(policyEnum.getPolicyName())
                .setDescription(policyEnum.getDescription())
                .setIsBuiltIn(true);

            codeToPolicy.put(policyEnum.getCode(), authorityPolicy);
        }
        authorityPolicyBaseMapper.insertBatchSomeColumn(new ArrayList<>(codeToPolicy.values()));

        List<PolicyStatement> statementList = new ArrayList<>();
        for (PolicyStatementEnum statementEnum : PolicyStatementEnum.values()) {
            PolicyStatement policyStatement = BeanPlusUtil.toBean(statementEnum, PolicyStatement.class)
                .setPolicyId(codeToPolicy.get(statementEnum.getCode()).getId());

            statementList.add(policyStatement);
        }
        policyStatementBaseMapper.insertBatchSomeColumn(statementList);

        WorksheetUserGroup userGroup = new WorksheetUserGroup().setName("超级管理员用户组")
            .setPolicyId(codeToPolicy.get(AuthorityPolicyEnum.SUPER_ADMIN.getCode()).getId())
            .setDescription("超级管理员用户组")
            .setIsScheduled(false)
            .setIsBuiltIn(true);
        worksheetUserGroupBaseMapper.insert(userGroup);

        User user = userBaseMapper.selectOne(new QueryWrap<User>().eq("is_del", 0).eq("is_built_in", 1));
        WorksheetUser worksheetUser = new WorksheetUser().setScore(65F)
            .setUserGroup(userGroup.getId().toString())
            .setName(user.getUserName())
            .setSubscriptionUrn("--")
            .setUserId(user.getId())
            .setTopicUrn("--")
            .setTotalStar(0L)
            .setEmail("--");
        worksheetUserBaseMapper.insert(worksheetUser);
    }

    /**
     * 创建rds_instance_info表，并初始化数据
     */
    @Override
    public void initRdsInstance() {
        rdsRepository.createRdsInstanceTable(databaseConfig.getConnectionInfo().getDbName(),
            ResourceNamingUtil.getPrefixCode());

        DatabaseConfig.ExclusivePackageRds exclusivePackageRds = databaseConfig.getExclusivePackageRds();
        String dbPassword = EncryptionUtil.encrypt(saasPwd, exclusivePackageRds.getPassword());

        RdsInstanceInfo rdsInstanceInfo = BeanPlusUtil.toBean(exclusivePackageRds, RdsInstanceInfo.class)
            .setRdsEndpoint(databaseConfig.getEndpoint())
            .setPassword(dbPassword);
        rdsInstanceInfoBaseMapper.insert(rdsInstanceInfo);
    }

    /**
     * 创建gaussdb_instance_info表，并初始化数据
     */
    @Override
    public void initGaussDBInstance() {
        rdsRepository.createGaussDBInstanceTable(databaseConfig.getConnectionInfo().getDbName(),
            ResourceNamingUtil.getPrefixCode());

        DatabaseConfig.ExclusivePackageGaussDb exclusivePackageGaussDb = databaseConfig.getExclusivePackageGaussDb();
        String dbPassword = EncryptionUtil.encrypt(saasPwd, exclusivePackageGaussDb.getPassword());

        GaussDBInstanceInfo gaussDBInstanceInfo =
            BeanPlusUtil.toBean(exclusivePackageGaussDb, GaussDBInstanceInfo.class)
                .setEndpoint(databaseConfig.getEndpoint())
                .setPassword(dbPassword);
        gaussDBInstanceInfoBaseMapper.insert(gaussDBInstanceInfo);
    }

    @Override
    public void rollbackDataBase() {
        log.info("========== start: 数据库回滚 ==========");

        // 主数据库表
        List<String> tables = dataRepository.findTables(databaseConfig.getConnectionInfo().getDbName());
        if (tables.size() > 0) {
            // 删除租户数据库
            List<String> tenantAppCodes = tenantAppMapper.getAllTenantAppCode();
            tenantAppCodes.remove(databaseConfig.getConnectionInfo().getDbName());

            log.info("删除租户数据库:{}", tenantAppCodes);
            if (tenantAppCodes.size() > 0) {
                dataRepository.deleteTenantConsoleDb(tenantAppCodes);
            }

            // 删除主数据库数据
            log.info("删除主数据库表数据:{}", tables);
            if (tables.size() > 0) {
                try {
                    dataRepository.setForeignKeyChecksInvalid();
                    dataRepository.deleteISVConsoleDb(tables, databaseConfig.getConnectionInfo().getDbName());
                    dataRepository.setForeignKeyChecksValid();
                } catch (Exception e) {
                    log.error("--------------数据库删除失败：{}----------", e.toString());
                    dataRepository.setForeignKeyChecksValid();
                    throw new BizException("删除数据库失败：{}", e);
                }
            }
        } else {
            log.info("当前数据库为空");
        }
        log.info("========== end: 数据库回滚 ==========");
    }

    @Override
    public Boolean canInitOrRollbackCceAndCse() {
        List<String> tables = dataRepository.findTables(databaseConfig.getConnectionInfo().getDbName());
        if (tables.size() == 0) {
            return false;
        }

        QueryWrapper<AppTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", 0).eq("type", 1);
        Long count = appTemplateBaseMapper.selectCount(queryWrapper);

        log.info("当前控制台应用数量：{}", count);
        return count == 1L;
    }

    /**
     * 初始化路由链路
     */
    private void initRouteLink() {
        RouteLink routeLink = new RouteLink();
        routeLink.setName("内置基线链路")
            .setDescription("内置基线链路")
            .setRouteLinkKey(RouteLinkConstant.ROUTE_LINK_KEY_BASE)
            .setIsBuiltIn(true);

        routeLinkBaseMapper.insert(routeLink);
    }

    /**
     * 初始化应用角色表 & 资源表 & 角色资源关系表
     *
     * @param appIdList 应用ID列表
     * @param subAppId 订阅应用ID
     */
    private void initAppRoleResource(List<Long> appIdList, long subAppId) {

        Long platformConsoleAppId = appIdList.get(0);

        initPlatformConsoleRoleResource(platformConsoleAppId);

        Long tenantConsoleAppId = appIdList.get(1);

        initTenantConsoleRoleResource(tenantConsoleAppId);

        initHotelRoleResource(appIdList.get(2));

        initBusinessRoleResource(appIdList.get(3));

        if (idaas.getApplicationHttpsMicro().getEnabled()) {
            initMicroRoleResource(appIdList.get(4));
        }

        // 平台侧本身作为租户，资源以及角色的初始化
        initSelfRoleResource(platformConsoleAppId, subAppId);
    }

    /**
     * 初始化Keycloak信息
     */
    private void initKeycloakInfo() {
        KeycloakInfo keyCloakInfo = new KeycloakInfo();
        keyCloakInfo.setUrl(idaas.getKeycloak().getUrl());
        keyCloakInfo.setAdminSecret(EncryptionUtil.encrypt(saasPwd, idaas.getKeycloak().getAdminSecret()));
        keycloakInfoBaseMapper.insert(keyCloakInfo);
    }

    /**
     * 初始化标签项
     */
    private void insertLabel() {
        dataRepository.insertLabel();
    }

    /**
     * 初始化 证书信息表（hsl_cert_store_info）
     *
     * @param saasPwd SaaS提供商密钥
     */
    private void tryInitCertStoreInfo(String saasPwd) {
        if (!ssl.isEnabled()) {
            return;
        }
        log.info(">>>>> 初始化 证书信息表（hsl_store_info）");
        CertStoreInfo hslCertStoreInfo = new CertStoreInfo();
        hslCertStoreInfo.setKeyStore(EncryptionUtil.encrypt(saasPwd, ssl.getKeyStore()))
            .setKeyStorePath(ssl.getKeyStorePath())
            .setKeyStorePwd(EncryptionUtil.encrypt(saasPwd, ssl.getKeyStorePwd()))
            .setTrustStore(EncryptionUtil.encrypt(saasPwd, ssl.getTrustStore()))
            .setTrustStorePath(ssl.getTrustStorePath())
            .setTrustStorePwd(EncryptionUtil.encrypt(saasPwd, ssl.getTrustStorePwd()));

        certStoreInfoBaseMapper.insert(hslCertStoreInfo);
    }

    /**
     * 初始化 skywalking信息表（hsl_skywalking_info）
     */
    private void tryInitSkywalking() {
        if (!skywalking.isEnabled()) {
            return;
        }
        log.info("初始化 skywalking信息表（hsl_skywalking_info）");
        SkywalkingInfo skywalkingInfo = new SkywalkingInfo();
        skywalkingInfo.setServer(skywalking.getServer())
            .setUrl(skywalking.getUrl())
            .setUiAndNginxReportHost(skywalking.getUiReportHost());
        skywalkingInfoBaseMapper.insert(skywalkingInfo);
    }

    /**
     * 初始化 LTS信息表（hsl_lts_info）
     */
    private void tryInitLtsInfo() {
        if (!lts.isEnabled()) {
            return;
        }
        log.info(">>>>> 初始化 LTS信息表（hsl_lts_info）");

        LtsInfo ltsInfo = new LtsInfo();
        ltsInfo.setRegion(iam.getRegion())
            .setProjectId(iam.getProjectId())
            .setEndpoint(lts.getEndpoint())
            .setAccessIp(lts.getIp())
            .setAccessPort(lts.getPort())
            .setDescription("LTS日志上报所需信息");

        ltsInfoRepository.insert(ltsInfo);
    }

    /**
     * 初始化升级镜像信息
     *
     * @param appIdList 应用ID列表
     */
    public void initUpgradeImage(List<Long> appIdList) {
        String swrEndpoint = endpointInfoBaseMapper.findSwrEndpoint(iam.getRegion());
        AppImage appImage = new AppImage();
        appImage.setAddress(swrEndpoint).setPreferred(false).setComponentVersion("0.0.2");

        // 租户侧控制台应用 授权
        initAndInsertImageInfoByLabel(appIdList.get(1), swrEndpoint, appImage, ComponentLabelEnum.AUTHORITY.getLabel(),
            upgradeSwr.getAuthoritySwrOrganization(), upgradeSwr.getAuthoritySwrName(),
            upgradeSwr.getAuthoritySwrVersion());

        // 酒店 订单
        initAndInsertImageInfoByName(appIdList.get(2), swrEndpoint, appImage, upgradeSwr.getOrderSwrName(),
            upgradeSwr.getOrderSwrOrganization(), upgradeSwr.getOrderSwrName(), upgradeSwr.getOrderSwrVersion());

        // 电商 订单
        initAndInsertImageInfoByName(appIdList.get(3), swrEndpoint, appImage, upgradeSwr.getOrderSwrName(),
            upgradeSwr.getOrderSwrOrganization(), upgradeSwr.getOrderSwrName(), upgradeSwr.getOrderSwrVersion());

        // 酒店 商品
        initAndInsertImageInfoByName(appIdList.get(2), swrEndpoint, appImage, upgradeSwr.getProductSwrName(),
            upgradeSwr.getProductSwrOrganization(), upgradeSwr.getProductSwrName(), upgradeSwr.getProductSwrVersion());

        // 电商 商品
        initAndInsertImageInfoByName(appIdList.get(3), swrEndpoint, appImage, upgradeSwr.getProductSwrName(),
            upgradeSwr.getProductSwrOrganization(), upgradeSwr.getProductSwrName(), upgradeSwr.getProductSwrVersion());

        // 平台ui镜像
        initAndInsertImageInfoByLabel(appIdList.get(0), swrEndpoint, appImage, ComponentLabelEnum.B_UI.getLabel(),
            upgradeSwr.getUiSwrOrganization(), upgradeSwr.getUiSwrName(), upgradeSwr.getUiSwrVersion());

        if (idaas.getApplicationHttpsMicro().getEnabled()) {
            continueInitTenantBusinessUpgradeImage(appIdList.get(4));
        }
    }

    /**
     * 初始化Redis信息
     */
    private void initRedis() {
        rdsRepository.createRedisInfoTable(databaseConfig.getConnectionInfo().getDbName(),
            ResourceNamingUtil.getPrefixCode());

        RedisInfo redisInfo = BeanPlusUtil.toBean(dcs, RedisInfo.class);
        redisInfo.setPassword(EncryptionUtil.encrypt(saasPwd, redisInfo.getPassword()));

        redisInfoBaseMapper.insert(redisInfo);
    }

    /**
     * 初始化订阅应用信息
     *
     * @param appId 应用ID
     */
    private void initHslSubscribedApp(Long appId) {
        AppTemplate appTemplate = appTemplateBaseMapper.selectById(appId);
        SubscribedApp hslSubscribedApp = BeanPlusUtil.toBean(appTemplate, SubscribedApp.class);
        hslSubscribedApp.setId(null);
        hslSubscribedApp.setAppId(appId).setStatus("正常").setType(null).setConsole(true).setArchitecture("微服务");
        subscribedAppBaseMapper.insert(hslSubscribedApp);
    }

    /**
     * 初始化 部署信息表（hsl_deployment_info）
     *
     * @param appIdList List of appId
     * @param saasPwd 平台侧口令
     */
    public void initDeploymentInfo(List<Long> appIdList, String saasPwd) {
        log.info(">>>>> 初始化 部署信息表（hsl_deployment_info）");

        // 初始化 IAM账号表（hsl_iam_account）
        Long iamId = initIamAccount(saasPwd);

        // 初始化 数据源信息表（hsl_rds_resource）
        Long rdsId = initRdsResource();

        // 初始化 CSE信息表（hsl_rds_resource）
        Long cseId = initCseInfo(saasPwd);

        // 初始化 CCE信息表（hsl_cce_info）
        Long cceId = initCceInfo();

        // 初始化 ELB信息表（hsl_elb_info） 前端 ELB 信息
        Long uiElbId = initUiElbInfo();

        // 初始化 OBS信息表（hsl_obs_info）
        Long obsId = initObsInfo();

        AppDeployment appDeployment = new AppDeployment();

        // 平台侧控制台应用
        appDeployment.setRegion(iam.getRegion())
            .setProjectId(iam.getProjectId())
            .setAppId(appIdList.get(0))
            .setIamId(iamId)
            .setRdsId(rdsId)
            .setCseId(cseId)
            .setCceId(cceId)
            .setGatewayElbId(uiElbId)
            .setUiElbId(uiElbId)
            .setObsId(obsId)
            .setEnterpriseProjectId(iam.getEnterpriseProjectId());
        appDeploymentBaseMapper.insert(appDeployment);

        // 租户侧控制台应用
        appDeployment.setUiElbId(null).setGatewayElbId(null).setAppId(appIdList.get(1)).setId(null);
        appDeploymentBaseMapper.insert(appDeployment);

        // 酒店应用
        appDeployment.setAppId(appIdList.get(2)).setId(null);
        appDeploymentBaseMapper.insert(appDeployment);

        // 电商应用
        appDeployment.setAppId(appIdList.get(3)).setId(null);
        appDeploymentBaseMapper.insert(appDeployment);

        // 微服务架构应用
        if (idaas.getApplicationHttpsMicro().getEnabled()) {
            appDeployment.setAppId(appIdList.get(4)).setId(null);
            appDeploymentBaseMapper.insert(appDeployment);
        }
    }

    /**
     * 初始化 OBS信息表（hsl_obs_info）
     *
     * @return 记录id
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initObsInfo() {
        log.info(">>>>> 初始化 OBS信息表（hsl_obs_info）");

        ObsInfo obsInfo = new ObsInfo();
        obsInfo.setRegion(iam.getRegion()).setObsBucketName(obs.getBucketName()).setDescription("保存应用logo");

        obsInfoBaseMapper.insert(obsInfo);

        return obsInfo.getId();
    }

    /**
     * 初始化 ELB信息表（hsl_elb_info） 前端 ELB 信息
     *
     * @return 记录id
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initUiElbInfo() {
        log.info(">>>>> 初始化 ELB信息表（hsl_elb_info） 前端 ELB 信息");

        ElbInfo elbInfo = new ElbInfo();
        elbInfo.setInstanceId(elb.getElbId())
            .setEip(elb.getElbEip())
            .setDescription("服务部署绑定 ELB")
            .setType(elb.getElbType())
            .setIp(elb.getElbIp());

        elbInfoBaseMapper.insert(elbInfo);

        return elbInfo.getId();
    }

    /**
     * 初始化 CCE信息表（hsl_cce_info）
     *
     * @return 记录id
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initCceInfo() {
        log.info(">>>>> 初始化 CCE信息表（hsl_cce_info）");

        CceInfo cceInfo = new CceInfo();
        cceInfo.setClusterId(cce.getClusterId())
            .setDescription("资源部署cce信息")
            .setEndpoint(endpoint.getCce())
            .setClusterName(cce.getClusterName())
            .setNodeIp(cce.getNodeIp())
            .setClusterVersion(cce.getClusterVersion());

        cceInfoBaseMapper.insert(cceInfo);

        return cceInfo.getId();
    }

    /**
     * 初始化 数据源信息表（hsl_rds_resource）
     *
     * @return 记录id
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initRdsResource() {
        log.info(">>>>> 初始化 数据源信息表（hsl_rds_resource）");
        rdsRepository.createRdsResourceTable(databaseConfig.getConnectionInfo().getDbName(),
            ResourceNamingUtil.getPrefixCode());

        DatabaseConfig.ConnectionInfo connectionInfo = databaseConfig.getConnectionInfo();
        String dbPassword = EncryptionUtil.encrypt(saasPwd, connectionInfo.getPassword());

        RdsResource rdsResource = new RdsResource().setInstanceName(connectionInfo.getInstanceName())
            .setDbPort(connectionInfo.getPort().toString())
            .setType(DataSourceTypeEnum.PLATFORM.getType())
            .setInstanceId(connectionInfo.getInstanceId())
            .setDbUsername(connectionInfo.getName())
            .setDbType(databaseConfig.getType())
            .setDbIp(connectionInfo.getIp())
            .setDbPassword(dbPassword)
            .setDbDriver(dbDriver)
            .setIsUsed(true);

        rdsResourceBaseMapper.insert(rdsResource);

        return rdsResource.getId();
    }

    /**
     * 初始化 CSE信息表（hsl_cse_info）
     *
     * @param saasPwd 平台侧口令
     * @return 记录id
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initCseInfo(String saasPwd) {
        log.info(">>>>> 初始化 CSE信息表（hsl_cse_info）");

        CseInfo cseInfoByType = setCseInfoByType(saasPwd, configDiscoveryFrame);

        cseInfoBaseMapper.insert(cseInfoByType);

        return cseInfoByType.getId();
    }

    /**
     * 初始化 EndPoint信息表（hsl_endpoint_info）
     */
    @Transactional(rollbackFor = Exception.class)
    public void initEndpointInfo() {
        log.info(">>>>> 初始化 EndPoint信息表（hsl_endpoint_info）");

        EndpointInfo endpointInfo = new EndpointInfo();
        endpointInfo.setRegion(iam.getRegion())
            .setProjectId(iam.getProjectId())
            .setIamEndpoint(endpoint.getIam())
            .setCceEndpoint(endpoint.getCce())
            .setSwrEndpoint(endpoint.getSwr())
            .setObsEndpoint(endpoint.getObs())
            .setLtsEndpoint(endpoint.getLts())
            .setEcsEndpoint(endpoint.getEcs())
            .setAomEndpoint(endpoint.getAom())
            .setDcsEndpoint(endpoint.getDcs())
            .setCesEndpoint(endpoint.getCes())
            .setRdsEndpoint(endpoint.getRds())
            .setSmnEndpoint(endpoint.getSmn())
            .setCseEndpoint(endpoint.getCse())
            .setElbEndpoint(endpoint.getElb())
            .setVpcEndpoint(endpoint.getVpc())
            .setWafEndpoint(endpoint.getWaf())
            .setCdnEndpoint(endpoint.getCdn())
            .setDnsEndpoint(endpoint.getDns())
            .setSfsTurboEndpoint(endpoint.getSfsTurbo());
        endpointInfoBaseMapper.insert(endpointInfo);
    }

    /**
     * 初始化 镜像表（hsl_image）
     *
     * @param appIdList List of appId
     */
    public void initImage(List<Long> appIdList) {
        log.info(">>>>> 初始化 镜像表（hsl_image）");

        String swrEndpoint = endpointInfoBaseMapper.findSwrEndpoint(iam.getRegion());
        AppImage appImage = new AppImage();

        Long platformConsoleAppId = appIdList.get(0);

        appImage.setAddress(swrEndpoint).setPreferred(true).setComponentVersion("0.0.1").setAppId(platformConsoleAppId);

        // 平台侧控制台应用：前端 & 网关 & 租户 & 授权 & 部署 & 升级 & 集成 & 运维 & 日志 & 认证
        initAndInsertImageInfoByLabel(platformConsoleAppId, swrEndpoint, appImage, ComponentLabelEnum.B_UI.getLabel(),
            swr.getUiSwrOrganization(), swr.getUiSwrName(), swr.getUiSwrVersion());

        initAndInsertImageInfoByLabel(platformConsoleAppId, swrEndpoint, appImage,
            ComponentLabelEnum.GATEWAY.getLabel(), swr.getGatewaySwrOrganization(), swr.getGatewaySwrName(),
            swr.getGatewaySwrVersion());

        initAndInsertImageInfoByLabel(platformConsoleAppId, swrEndpoint, appImage, ComponentLabelEnum.TENANT.getLabel(),
            swr.getTenantSwrOrganization(), swr.getTenantSwrName(), swr.getTenantSwrVersion());

        initAndInsertImageInfoByLabel(platformConsoleAppId, swrEndpoint, appImage,
            ComponentLabelEnum.AUTHORITY.getLabel(), swr.getAuthoritySwrOrganization(), swr.getAuthoritySwrName(),
            swr.getAuthoritySwrVersion());

        initAndInsertImageInfoByLabel(platformConsoleAppId, swrEndpoint, appImage,
            ComponentLabelEnum.DEPLOYMENT.getLabel(), swr.getDeploymentSwrOrganization(), swr.getDeploymentSwrName(),
            swr.getDeploymentSwrVersion());

        initAndInsertImageInfoByLabel(platformConsoleAppId, swrEndpoint, appImage,
            ComponentLabelEnum.UPGRADE.getLabel(), swr.getUpgradeSwrOrganization(), swr.getUpgradeSwrName(),
            swr.getUpgradeSwrVersion());

        initAndInsertImageInfoByLabel(platformConsoleAppId, swrEndpoint, appImage,
            ComponentLabelEnum.INTEGRATED.getLabel(), swr.getIntegratedSwrOrganization(), swr.getIntegratedSwrName(),
            swr.getIntegratedSwrVersion());

        initAndInsertImageInfoByLabel(platformConsoleAppId, swrEndpoint, appImage,
            ComponentLabelEnum.MAINTENANCE.getLabel(), swr.getMaintenanceSwrOrganization(), swr.getMaintenanceSwrName(),
            swr.getMaintenanceSwrVersion());

        initAndInsertImageInfoByLabel(platformConsoleAppId, swrEndpoint, appImage, ComponentLabelEnum.LOG.getLabel(),
            swr.getLogSwrOrganization(), swr.getLogSwrName(), swr.getLogSwrVersion());

        initAndInsertImageInfoByLabel(platformConsoleAppId, swrEndpoint, appImage, ComponentLabelEnum.AUTH.getLabel(),
            swr.getAuthSwrOrganization(), swr.getAuthSwrName(), swr.getAuthSwrVersion());

        initAndInsertImageInfoByLabel(platformConsoleAppId, swrEndpoint, appImage,
            ComponentLabelEnum.OPERATION.getLabel(), swr.getOperationSwrOrganization(), swr.getOperationSwrName(),
            swr.getOperationSwrVersion());

        initAndInsertImageInfoByLabel(platformConsoleAppId, swrEndpoint, appImage,
            ComponentLabelEnum.MEASUREMENT.getLabel(), swr.getMeasurementSwrOrganization(), swr.getMeasurementSwrName(),
            swr.getMeasurementSwrVersion());

        initAndInsertImageInfoByLabel(platformConsoleAppId, swrEndpoint, appImage, ComponentLabelEnum.JOB.getLabel(),
            swr.getJobSwrOrganization(), swr.getJobSwrName(), swr.getJobSwrVersion());

        // 初始化租户控制台应用镜像信息
        continueInitTenantConsoleImage(appIdList.get(1));

        // 初始化业务应用镜像信息
        continueInitTenantBusinessImage(appIdList.get(2), AppNameEnum.HOTEL);
        continueInitTenantBusinessImage(appIdList.get(3), AppNameEnum.E_COMMERCE);

        if (idaas.getApplicationHttpsMicro().getEnabled()) {
            continueInitTenantBusinessImage(appIdList.get(4), AppNameEnum.MICRO);
        }

    }

    /**
     * 初始化 租户控制台应用镜像信息（hsl_image）
     *
     * @param appId 应用ID
     */
    public void continueInitTenantConsoleImage(Long appId) {
        String swrEndpoint = endpointInfoBaseMapper.findSwrEndpoint(iam.getRegion());
        AppImage appImage = new AppImage();
        appImage.setAddress(swrEndpoint).setPreferred(true).setComponentVersion("0.0.1").setAppId(appId);

        // 租户侧控制台应用： 网关 & 租户 & 授权 & 日志 & 认证
        initAndInsertImageInfoByLabel(appId, swrEndpoint, appImage, ComponentLabelEnum.GATEWAY.getLabel(),
            swr.getGatewaySwrOrganization(), swr.getGatewaySwrName(), swr.getGatewaySwrVersion());

        initAndInsertImageInfoByLabel(appId, swrEndpoint, appImage, ComponentLabelEnum.TENANT.getLabel(),
            swr.getTenantSwrOrganization(), swr.getTenantSwrName(), swr.getTenantSwrVersion());

        initAndInsertImageInfoByLabel(appId, swrEndpoint, appImage, ComponentLabelEnum.AUTHORITY.getLabel(),
            swr.getAuthoritySwrOrganization(), swr.getAuthoritySwrName(), swr.getAuthoritySwrVersion());

        initAndInsertImageInfoByLabel(appId, swrEndpoint, appImage, ComponentLabelEnum.LOG.getLabel(),
            swr.getLogSwrOrganization(), swr.getLogSwrName(), swr.getLogSwrVersion());

        initAndInsertImageInfoByLabel(appId, swrEndpoint, appImage, ComponentLabelEnum.AUTH.getLabel(),
            swr.getAuthSwrOrganization(), swr.getAuthSwrName(), swr.getAuthSwrVersion());
    }

    /**
     * 初始化 租户业务应用镜像信息（hsl_image）
     *
     * @param appId 应用ID
     * @param appNameEnum 应用名称枚举
     */
    public void continueInitTenantBusinessImage(Long appId, AppNameEnum appNameEnum) {
        String swrEndpoint = endpointInfoBaseMapper.findSwrEndpoint(iam.getRegion());
        AppImage appImage = new AppImage();
        appImage.setAddress(swrEndpoint).setPreferred(true).setComponentVersion("0.0.1").setAppId(appId);

        // 租户侧业务应用： 订单 & 商品 & ui
        initAndInsertImageInfoByName(appId, swrEndpoint, appImage, swr.getOrderSwrName(), swr.getOrderSwrOrganization(),
            swr.getOrderSwrName(), swr.getOrderSwrVersion());

        initAndInsertImageInfoByName(appId, swrEndpoint, appImage, swr.getProductSwrName(),
            swr.getProductSwrOrganization(), swr.getProductSwrName(), swr.getProductSwrVersion());

        if (AppNameEnum.HOTEL.getName().equals(appNameEnum.getName())) {
            initAndInsertImageInfoByName(appId, swrEndpoint, appImage, swr.getHotelUiSwrName(),
                swr.getHotelUiSwrOrganization(), swr.getHotelUiSwrName(), swr.getHotelUiSwrVersion());
        } else if (AppNameEnum.E_COMMERCE.getName().equals(appNameEnum.getName())) {
            initAndInsertImageInfoByName(appId, swrEndpoint, appImage, swr.getECommerceUiSwrName(),
                swr.getECommerceUiSwrOrganization(), swr.getECommerceUiSwrName(), swr.getECommerceUiSwrVersion());
        } else if (AppNameEnum.MICRO.getName().equals(appNameEnum.getName())) {
            initAndInsertImageInfoByName(appId, swrEndpoint, appImage, swr.getMicroUiSwrName(),
                    swr.getMicroUiSwrOrganization(), swr.getMicroUiSwrName(), swr.getMicroUiSwrVersion());
        }
    }

    /**
     * 初始化 租户业务应用升级镜像信息（hsl_image）
     *
     * @param appId 应用ID
     */
    public void continueInitTenantBusinessUpgradeImage(Long appId) {
        String swrEndpoint = endpointInfoBaseMapper.findSwrEndpoint(iam.getRegion());
        AppImage appImage = new AppImage();
        appImage.setAddress(swrEndpoint).setPreferred(false).setComponentVersion("0.0.2").setAppId(appId);

        initAndInsertImageInfoByName(appId, swrEndpoint, appImage, upgradeSwr.getOrderSwrName(),
            upgradeSwr.getOrderSwrOrganization(), upgradeSwr.getOrderSwrName(), upgradeSwr.getOrderSwrVersion());

        initAndInsertImageInfoByName(appId, swrEndpoint, appImage, upgradeSwr.getProductSwrName(),
            upgradeSwr.getProductSwrOrganization(), upgradeSwr.getProductSwrName(), upgradeSwr.getProductSwrVersion());
    }

    /**
     * 初始化并插入镜像信息
     *
     * @param appId 应用ID
     * @param swrEndpoint SWR终端地址
     * @param appImage 镜像信息
     * @param label 组件标志
     * @param swrOrganization SWR组织名
     * @param swrName 镜像名称
     * @param swrVersion 镜像版本
     */
    private void initAndInsertImageInfoByLabel(Long appId, String swrEndpoint, AppImage appImage, String label,
        String swrOrganization, String swrName, String swrVersion) {
        String imageFullName;
        Long componentId = componentInfoMapper.findComponentId(appId, label);
        log.info("根据应用ID：{}，组件名称：{}，查找镜像对应的组件ID为：{}", appId, label, componentId);
        imageFullName = swrEndpoint + "/" + swrOrganization + "/" + swrName + ":" + swrVersion;
        appImage.setName(swrName)
            .setOrganization(swrOrganization)
            .setImage(imageFullName)
            .setComponentId(componentId)
            .setVersion(swrVersion)
            .setAppId(appId)
            .setId(null);
        appImageBaseMapper.insert(appImage);
    }

    /**
     * 初始化并插入镜像信息
     *
     * @param appId 应用ID
     * @param swrEndpoint SWR终端地址
     * @param appImage 镜像信息
     * @param componentName 组件名称
     * @param swrOrganization SWR组织名
     * @param swrName 镜像名称
     * @param swrVersion 镜像版本
     */
    private void initAndInsertImageInfoByName(Long appId, String swrEndpoint, AppImage appImage, String componentName,
        String swrOrganization, String swrName, String swrVersion) {
        String imageFullName;
        Long componentId = componentInfoMapper.findComponentIdByName(appId, componentName);
        log.info("根据应用ID：{}，组件名称：{}，查找镜像对应的组件ID为：{}", appId, componentName, componentId);
        imageFullName = swrEndpoint + "/" + swrOrganization + "/" + swrName + ":" + swrVersion;
        appImage.setName(swrName)
            .setOrganization(swrOrganization)
            .setImage(imageFullName)
            .setComponentId(componentId)
            .setVersion(swrVersion)
            .setAppId(appId)
            .setId(null);
        appImageBaseMapper.insert(appImage);
    }

    /**
     * 初始化 组件表（hsl_component_info）
     *
     * @param appIdList List of appId
     */
    public void initAppComponent(List<Long> appIdList) {
        log.info(">>>>> 初始化 组件表（hsl_component_info）");

        AppComponent appComponent = new AppComponent();
        appComponent.setType("MicroService").setRuntime("Java8").setFramework("SpringCloud");

        Long platformConsoleAppId = appIdList.get(0);

        // 平台侧控制台应用：前端 & 网关 & 租户 & 授权 & 部署 & 升级 & 集成 & 运维 & 日志 & 认证。
        generateComponentInfo(appComponent, platformConsoleAppId, swr.getUiSwrName(), swr.getUiServerPort(),
            swr.getUiAccessPrefix(), ComponentLabelEnum.B_UI);

        generateComponentInfo(appComponent, platformConsoleAppId, swr.getGatewaySwrName(), swr.getGatewayServerPort(),
            "/", ComponentLabelEnum.GATEWAY);

        generateComponentInfo(appComponent, platformConsoleAppId, swr.getTenantSwrName(), swr.getTenantServerPort(),
            swr.getTenantAccessPrefix(), ComponentLabelEnum.TENANT);

        generateComponentInfo(appComponent, platformConsoleAppId, swr.getAuthoritySwrName(),
            swr.getAuthorityServerPort(), swr.getAuthorityAccessPrefix(), ComponentLabelEnum.AUTHORITY);

        generateComponentInfo(appComponent, platformConsoleAppId, swr.getDeploymentSwrName(),
            swr.getDeploymentServerPort(), swr.getDeploymentAccessPrefix(), ComponentLabelEnum.DEPLOYMENT);

        generateComponentInfo(appComponent, platformConsoleAppId, swr.getUpgradeSwrName(), swr.getUpgradeServerPort(),
            swr.getUpgradeAccessPrefix(), ComponentLabelEnum.UPGRADE);

        generateComponentInfo(appComponent, platformConsoleAppId, swr.getIntegratedSwrName(),
            swr.getIntegratedServerPort(), swr.getIntegratedAccessPrefix(), ComponentLabelEnum.INTEGRATED);

        generateComponentInfo(appComponent, platformConsoleAppId, swr.getMaintenanceSwrName(),
            swr.getMaintenanceServerPort(), swr.getMaintenanceAccessPrefix(), ComponentLabelEnum.MAINTENANCE);

        generateComponentInfo(appComponent, platformConsoleAppId, swr.getLogSwrName(), swr.getLogServerPort(),
            swr.getLogAccessPrefix(), ComponentLabelEnum.LOG);

        generateComponentInfo(appComponent, platformConsoleAppId, swr.getAuthSwrName(), swr.getAuthServerPort(),
            swr.getAuthAccessPrefix(), ComponentLabelEnum.AUTH);

        generateComponentInfo(appComponent, platformConsoleAppId, swr.getOperationSwrName(),
            swr.getOperationServerPort(), swr.getOperationAccessPrefix(), ComponentLabelEnum.OPERATION);

        generateComponentInfo(appComponent, platformConsoleAppId, swr.getMeasurementSwrName(),
            swr.getMeasurementServerPort(), swr.getMeasurementAccessPrefix(), ComponentLabelEnum.MEASUREMENT);

        generateComponentInfo(appComponent, platformConsoleAppId, swr.getJobSwrName(), swr.getJobServerPort(),
            swr.getJobAccessPrefix(), ComponentLabelEnum.JOB);

        // 初始化租户侧控制台应用组件信息
        continueInitTenantConsoleComponentInfo(appIdList.get(1));

        // 初始化业务应用组件信息
        continueInitBusinessComponentInfo(appIdList);
    }

    /**
     * 初始化 租户侧控制台应用组件信息（hsl_component_info）
     *
     * @param appId 租户侧控制台应用ID
     */
    public void continueInitTenantConsoleComponentInfo(Long appId) {

        AppComponent appComponent = new AppComponent();
        appComponent.setType("MicroService").setRuntime("Java8").setFramework("SpringCloud");

        // 租户侧控制台应用：网关 & 租户 & 授权 & 日志 & 认证
        generateComponentInfo(appComponent, appId, swr.getGatewaySwrName(), swr.getGatewayServerPort(), "/",
            ComponentLabelEnum.GATEWAY);

        generateComponentInfo(appComponent, appId, swr.getTenantSwrName(), swr.getTenantServerPort(),
            swr.getTenantAccessPrefix(), ComponentLabelEnum.TENANT);

        generateComponentInfo(appComponent, appId, swr.getAuthoritySwrName(), swr.getAuthorityServerPort(),
            swr.getAuthorityAccessPrefix(), ComponentLabelEnum.AUTHORITY);

        generateComponentInfo(appComponent, appId, swr.getLogSwrName(), swr.getLogServerPort(),
            swr.getLogAccessPrefix(), ComponentLabelEnum.LOG);

        generateComponentInfo(appComponent, appId, swr.getAuthSwrName(), swr.getAuthServerPort(),
            swr.getAuthAccessPrefix(), ComponentLabelEnum.AUTH);
    }

    /**
     * 初始化 电商应用、酒店应用的组件信息（hsl_component_info）
     *
     * @param appIdList 业务应用ID列表
     */
    public void continueInitBusinessComponentInfo(List<Long> appIdList) {

        initBusinessAppComponent(appIdList.get(2), AppNameEnum.HOTEL);

        initBusinessAppComponent(appIdList.get(3), AppNameEnum.E_COMMERCE);

        if (idaas.getApplicationHttpsMicro().getEnabled()) {
            initBusinessAppComponent(appIdList.get(4), AppNameEnum.MICRO);
        }
    }

    /**
     * 初始化 业务应用组件信息（hsl_component_info）
     *
     * @param appId 业务应用ID
     * @param appNameEnum 应用名称枚举
     */
    public void initBusinessAppComponent(Long appId, AppNameEnum appNameEnum) {
        AppComponent appComponent = new AppComponent();
        appComponent.setType("MicroService").setRuntime("Java8").setFramework("SpringCloud");

        // 业务应用 微服务：订单 & 商品 & ui
        generateComponentInfo(appComponent, appId, swr.getOrderSwrName(), swr.getOrderServerPort(),
            swr.getOrderAccessPrefix(), ComponentLabelEnum.BUSINESS);

        generateComponentInfo(appComponent, appId, swr.getProductSwrName(), swr.getProductServerPort(),
            swr.getProductAccessPrefix(), ComponentLabelEnum.BUSINESS);

        if (AppNameEnum.HOTEL.getName().equals(appNameEnum.getName())) {
            generateComponentInfo(appComponent, appId, swr.getHotelUiSwrName(), swr.getHotelUiServerPort(),
                swr.getHotelUiAccessPrefix(), ComponentLabelEnum.B_UI);
        } else if (AppNameEnum.E_COMMERCE.getName().equals(appNameEnum.getName())) {
            generateComponentInfo(appComponent, appId, swr.getECommerceUiSwrName(), swr.getECommerceUiServerPort(),
                swr.getECommerceUiAccessPrefix(), ComponentLabelEnum.B_UI);
        } else if (AppNameEnum.MICRO.getName().equals(appNameEnum.getName())) {
            generateComponentInfo(appComponent, appId, swr.getMicroUiSwrName(), swr.getMicroUiServerPort(),
                swr.getMicroUiAccessPrefix(), ComponentLabelEnum.B_UI);
        }
    }

    /**
     * 生成组件信息
     *
     * @param appComponent 组件信息
     * @param appId 应用ID
     * @param componentName 组件名
     * @param serverPort 组件服务端口号
     * @param contextPath 组件访问前缀
     * @param label 组件标志
     */
    private void generateComponentInfo(AppComponent appComponent, Long appId, String componentName, Integer serverPort,
        String contextPath, ComponentLabelEnum label) {
        appComponent.setName(componentName)
            .setPort(serverPort)
            .setContextPath(contextPath)
            .setLabel(label.getLabel())
            .setAppId(appId)
            .setId(null);
        componentInfoMapper.insert(appComponent);
    }

    /**
     * 初始化 组件上下游（hsl_component_relationship）
     */
    public void initComponentRelationship() {
        // 查酒店和电商应用的id
        Long hotelId = appTemplateBaseMapper.selectIdByNameAndType(idaas.getApplicationHttpsHotel().getName(),
            AppTypeEnum.BUSINESS.getLabel());
        Long businessId = appTemplateBaseMapper.selectIdByNameAndType(idaas.getApplicationHttpsBusiness().getName(),
            AppTypeEnum.BUSINESS.getLabel());

        // 查找对应应用下的订单和商品的组件id
        Long hotelOrderComponentId = componentInfoMapper.findComponentIdByName(hotelId, "saaslanding-order");
        Long hotelProductComponentId = componentInfoMapper.findComponentIdByName(hotelId, "saaslanding-product");
        Long businessOrderComponentId = componentInfoMapper.findComponentIdByName(businessId, "saaslanding-order");
        Long businessProductComponentId = componentInfoMapper.findComponentIdByName(businessId, "saaslanding-product");

        List<ComponentRelationship> relationships = new ArrayList<>();
        List<Long> componentIdList = componentInfoMapper.findComponentIdByLabel();

        // 保存租户全共享策略的上下游关系
        initRelationshipByStrategy(relationships, componentIdList, hotelOrderComponentId, hotelProductComponentId,
            businessOrderComponentId, businessProductComponentId, AppTypeEnum.SAAS,
            ManageDeployStrategyEnum.SHARED.getStrategy());

        // 保存租户独享策略的上下游关系
        initRelationshipByStrategy(relationships, componentIdList, hotelOrderComponentId, hotelProductComponentId,
            businessOrderComponentId, businessProductComponentId, AppTypeEnum.TENANT,
            ManageDeployStrategyEnum.EXCLUSIVE.getStrategy());

        componentInfoMapper.batchSaveComponentRelationship(relationships);

        if (idaas.getApplicationHttpsMicro().getEnabled()) {
            initMicroAppComponentRelationship(idaas.getApplicationHttpsMicro().getId());
        }
    }

    /**
     * 初始化 微服务架构应用组件上下游（hsl_component_relationship）
     *
     * @param appId 应用ID
     */
    public void initMicroAppComponentRelationship(Long appId) {

        // 查找对应应用下的订单和商品的组件id
        Long microOrderComponentId = componentInfoMapper.findComponentIdByName(appId, "saaslanding-order");
        Long microProductComponentId = componentInfoMapper.findComponentIdByName(appId, "saaslanding-product");

        List<ComponentRelationship> relationships = new ArrayList<>();

        // 保存订单和商品组件的上下游关系（全共享 & 独享）
        generateComponentRelationship(relationships, microOrderComponentId, microProductComponentId,
            ManageDeployStrategyEnum.SHARED.getStrategy());
        generateComponentRelationship(relationships, microOrderComponentId, microProductComponentId,
            ManageDeployStrategyEnum.EXCLUSIVE.getStrategy());

        componentInfoMapper.batchSaveComponentRelationship(relationships);
    }

    /**
     * 依据部署策略，初始化组件上下游关系
     *
     * @param relationships 组件上下游关系列表
     * @param componentIdList 组件ID列表
     * @param hotelOrderComponentId 酒店应用订单组件ID
     * @param hotelProductComponentId 酒店应用商品组件ID
     * @param businessOrderComponentId 电商应用订单组件ID
     * @param businessProductComponentId 电商应用商品组件ID
     * @param appType 应用类型（平台侧 / 租户侧控制台 / 租户侧业务）
     * @param strategy 部署策略
     */
    private void initRelationshipByStrategy(List<ComponentRelationship> relationships, List<Long> componentIdList,
        Long hotelOrderComponentId, Long hotelProductComponentId, Long businessOrderComponentId,
        Long businessProductComponentId, AppTypeEnum appType, String strategy) {
        // 存全共享策略的上下游关系
        Long saasAppId = appTemplateBaseMapper.selectIdByType(appType.getLabel());
        Long tenantGatewayComponentId = componentInfoMapper.findComponentIdByName(saasAppId, "saaslanding-gateway");
        // 存网关和其他组件的上下游关系
        for (Long componentId : componentIdList) {
            generateComponentRelationship(relationships, tenantGatewayComponentId, componentId, strategy);
        }

        // 存酒店应用、电商应用的订单和商品组件的上下游关系
        generateComponentRelationship(relationships, hotelOrderComponentId, hotelProductComponentId, strategy);
        generateComponentRelationship(relationships, businessOrderComponentId, businessProductComponentId, strategy);
    }

    /**
     * 生成组件上下游关系
     *
     * @param relationships 组件上下游关系列表
     * @param upstreamComponentId 上游组件ID
     * @param downstreamComponentId 下游组件ID
     * @param strategy 部署策略
     */
    private void generateComponentRelationship(List<ComponentRelationship> relationships, Long upstreamComponentId,
        Long downstreamComponentId, String strategy) {
        ComponentRelationship componentRelationship = new ComponentRelationship();
        componentRelationship.setDeploymentStrategy(strategy);
        componentRelationship.setId(uidGenerator.getUid());
        componentRelationship.setUpstreamComponentId(upstreamComponentId);
        componentRelationship.setDownstreamComponentId(downstreamComponentId);
        relationships.add(componentRelationship);
    }

    /**
     * 初始化 IMC配置参数表（hsl_imc_params）
     *
     * @param saasPwd 平台侧口令
     */
    @Transactional(rollbackFor = Exception.class)
    public void initImcParams(String saasPwd) {
        log.info(">>>>> 初始化 IMC配置参数表（hsl_imc_params）");
        String token = EncryptionUtil.createSalt();
        String signKey = EncryptionUtil.createSalt();
        String tokenEncryptionKey = EncryptionUtil.createSalt();

        String imcToken = EncryptionUtil.encrypt(saasPwd, token);
        String imcSignKey = EncryptionUtil.encrypt(saasPwd, signKey);
        String imcEncryptionKey = EncryptionUtil.encrypt(saasPwd, tokenEncryptionKey);

        ImcParams imcParams = new ImcParams();
        imcParams.setImcToken(imcToken)
            .setImcSignKey(imcSignKey)
            .setImcEncryptionKey(imcEncryptionKey)
            .setImcHmacSha256("HmacSHA256")
            .setImcEncryptAlgorithm("AES/GCM/NoPadding")
            .setImcEncryptKeyAlgorithm("AES");

        imcParamsBaseMapper.insert(imcParams);
    }

    /**
     * 初始化 套餐表（hsl_app_package）
     *
     * @param appIdList List of appId
     */
    @Transactional(rollbackFor = Exception.class)
    public void initAppPackageResource(List<Long> appIdList) {
        log.info(">>>>> 初始化 套餐表（hsl_app_package）以及 套餐资源表（hsl_app_package_resource）");

        AppPackage basicPackage = new AppPackage();
        basicPackage.setType(PackageTypeEnum.BASIC.getDesc())
            .setEnterpriseSize("中小型")
            .setMultiTenantModel(DbMultiTenantMode.COLUMN.getMode() + "_" + AppMultiTenantMode.SHARED.getMode())
            .setAppMultiTenantMode(AppMultiTenantMode.SHARED.getMode())
            .setDbMultiTenantMode(DbMultiTenantMode.COLUMN.getMode())
            .setIfSupportFileSystem(false)
            .setIsExpand(false)
            .setIfSupportLicenseMgmt(false)
            .setStatus(true);

        AppPackage professionalPackage = new AppPackage();
        professionalPackage.setType(PackageTypeEnum.PROFESSIONAL.getDesc())
            .setEnterpriseSize("中大型")
            .setMultiTenantModel(DbMultiTenantMode.SCHEMA.getMode() + "_" + AppMultiTenantMode.NAMESPACE.getMode())
            .setAppMultiTenantMode(AppMultiTenantMode.NAMESPACE.getMode())
            .setDbMultiTenantMode(DbMultiTenantMode.SCHEMA.getMode())
            .setIfSupportFileSystem(false)
            .setIsExpand(false)
            .setIfSupportLicenseMgmt(false)
            .setStatus(true);

        AppPackage premiumPackage = new AppPackage();
        premiumPackage.setType(PackageTypeEnum.PREMIUM.getDesc())
            .setEnterpriseSize("大型")
            .setMultiTenantModel(DbMultiTenantMode.DATASOURCE.getMode() + "_" + AppMultiTenantMode.NAMESPACE.getMode())
            .setAppMultiTenantMode(AppMultiTenantMode.NAMESPACE.getMode())
            .setDbMultiTenantMode(DbMultiTenantMode.DATASOURCE.getMode())
            .setIfSupportFileSystem(false)
            .setIsExpand(false)
            .setIfSupportLicenseMgmt(false)
            .setStatus(true);

        // 酒店应用
        Long hotelAppId = appIdList.get(2);
        basicPackage.setAppId(hotelAppId);
        appPackageBaseMapper.insert(basicPackage);
        professionalPackage.setAppId(hotelAppId);
        appPackageBaseMapper.insert(professionalPackage);
        premiumPackage.setAppId(hotelAppId);
        appPackageBaseMapper.insert(premiumPackage);

        // 初始化酒店套餐资源表
        initHotelPackageResources(basicPackage.getId(), professionalPackage.getId(), premiumPackage.getId());

        // 电商应用
        Long busAppId = appIdList.get(3);
        basicPackage.setAppId(busAppId).setId(null);
        appPackageBaseMapper.insert(basicPackage);
        professionalPackage.setAppId(busAppId).setId(null);
        appPackageBaseMapper.insert(professionalPackage);
        premiumPackage.setAppId(busAppId).setId(null);
        appPackageBaseMapper.insert(premiumPackage);

        // 初始化电商套餐资源表
        initBusinessPackageResources(basicPackage.getId(), professionalPackage.getId(), premiumPackage.getId());

        // 微服务架构应用
        if (idaas.getApplicationHttpsMicro().getEnabled()) {
            Long microAppId = appIdList.get(4);
            basicPackage.setAppId(microAppId).setId(null);
            appPackageBaseMapper.insert(basicPackage);
            professionalPackage.setAppId(microAppId).setId(null);
            appPackageBaseMapper.insert(professionalPackage);
            premiumPackage.setAppId(microAppId).setId(null);
            appPackageBaseMapper.insert(premiumPackage);

            // 初始化微服务套餐资源表
            initMicroPackageResources(basicPackage.getId(), professionalPackage.getId(), premiumPackage.getId());
        }

    }

    /**
     * 初始化微服务套餐资源数据
     *
     * @param basicPackageId 基础版套餐ID
     * @param professionalPackageId 专业版套餐ID
     * @param premiumPackageId 尊享版套餐ID
     */
    private void initMicroPackageResources(Long basicPackageId, Long professionalPackageId, Long premiumPackageId) {
        // 初始化基础版 应用套餐资源数据
        List<AppPackageResource> list = new ArrayList<>();
        list.add(new AppPackageResource(basicPackageId, 1496754892604178469L));
        list.add(new AppPackageResource(basicPackageId, 1496754892604178470L));
        list.add(new AppPackageResource(basicPackageId, 1504747118356259653L));
        list.add(new AppPackageResource(basicPackageId, 1504747118356259654L));
        list.add(new AppPackageResource(basicPackageId, 1504747118356259655L));
        list.add(new AppPackageResource(basicPackageId, 1504747118356259656L));
        list.add(new AppPackageResource(basicPackageId, 1496746245569441585L));

        list.add(new AppPackageResource(basicPackageId, 1517321342417182125L));
        list.add(new AppPackageResource(basicPackageId, 1517321382632025290L));
        list.add(new AppPackageResource(basicPackageId, 1517321382632025291L));
        list.add(new AppPackageResource(basicPackageId, 1517321382632025292L));
        list.add(new AppPackageResource(basicPackageId, 1517321382632025293L));
        list.add(new AppPackageResource(basicPackageId, 1517321382632025294L));
        list.add(new AppPackageResource(basicPackageId, 1517321382632025295L));
        list.add(new AppPackageResource(basicPackageId, 1517321382632025296L));

        appPackageResourceBaseMapper.insertBatchSomeColumn(list);

        // 初始化专业版 应用套餐资源数据
        list = new ArrayList<>();
        list.add(new AppPackageResource(professionalPackageId, 1496754892604178469L));
        list.add(new AppPackageResource(professionalPackageId, 1496754892604178470L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118356259653L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118356259654L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118356259655L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118356259656L));
        list.add(new AppPackageResource(professionalPackageId, 1496746245569441585L));
        list.add(new AppPackageResource(professionalPackageId, 1496754892604178467L));
        list.add(new AppPackageResource(professionalPackageId, 1496754892604178468L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118356259650L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118356259651L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118356259652L));

        list.add(new AppPackageResource(professionalPackageId, 1517321342417182125L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025290L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025291L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025292L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025293L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025294L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025295L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025296L));

        list.add(new AppPackageResource(professionalPackageId, 1517321342417182123L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342417182124L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025281L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025282L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025283L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025284L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025285L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025286L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025287L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025288L));
        list.add(new AppPackageResource(professionalPackageId, 1517321382632025289L));
        list.add(new AppPackageResource(professionalPackageId, 1517321134654654641L));

        appPackageResourceBaseMapper.insertBatchSomeColumn(list);

        // 初始化尊享版 应用套餐资源数据
        list = new ArrayList<>();
        list.add(new AppPackageResource(premiumPackageId, 1496754892604178469L));
        list.add(new AppPackageResource(premiumPackageId, 1496754892604178470L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118356259653L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118356259654L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118356259655L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118356259656L));
        list.add(new AppPackageResource(premiumPackageId, 1496746245569441585L));
        list.add(new AppPackageResource(premiumPackageId, 1496754892604178467L));
        list.add(new AppPackageResource(premiumPackageId, 1496754892604178468L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118356259650L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118356259651L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118356259652L));

        list.add(new AppPackageResource(premiumPackageId, 1517321342417182125L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025290L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025291L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025292L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025293L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025294L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025295L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025296L));

        list.add(new AppPackageResource(premiumPackageId, 1517321342417182123L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342417182124L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025281L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025282L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025283L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025284L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025285L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025286L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025287L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025288L));
        list.add(new AppPackageResource(premiumPackageId, 1517321382632025289L));
        list.add(new AppPackageResource(premiumPackageId, 1517321134654654641L));

        appPackageResourceBaseMapper.insertBatchSomeColumn(list);
    }

    /**
     * 初始化酒店套餐资源数据
     *
     * @param basicPackageId 基础版套餐ID
     * @param professionalPackageId 专业版套餐ID
     * @param premiumPackageId 尊享版套餐ID
     */
    private void initHotelPackageResources(Long basicPackageId, Long professionalPackageId, Long premiumPackageId) {
        // 初始化基础版 应用套餐资源数据
        List<AppPackageResource> list = new ArrayList<>();
        list.add(new AppPackageResource(basicPackageId, 1496754892604178461L));
        list.add(new AppPackageResource(basicPackageId, 1496754892604178462L));
        list.add(new AppPackageResource(basicPackageId, 1504747118353258921L));
        list.add(new AppPackageResource(basicPackageId, 1504747118353258922L));
        list.add(new AppPackageResource(basicPackageId, 1504747118353258923L));
        list.add(new AppPackageResource(basicPackageId, 1504747118353258924L));
        list.add(new AppPackageResource(basicPackageId, 1496746245218453164L));

        list.add(new AppPackageResource(basicPackageId, 1517321342507028301L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507028302L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507028303L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507028304L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507028305L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507028306L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507028307L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507132129L));

        appPackageResourceBaseMapper.insertBatchSomeColumn(list);

        // 初始化专业版 应用套餐资源数据
        list = new ArrayList<>();
        list.add(new AppPackageResource(professionalPackageId, 1496754892604178461L));
        list.add(new AppPackageResource(professionalPackageId, 1496754892604178462L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258921L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258922L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258923L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258924L));
        list.add(new AppPackageResource(professionalPackageId, 1496754892604178459L));
        list.add(new AppPackageResource(professionalPackageId, 1496754892604178460L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258918L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258919L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258920L));
        list.add(new AppPackageResource(professionalPackageId, 1496746245218453164L));

        list.add(new AppPackageResource(professionalPackageId, 1517321342507028292L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028293L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028294L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028295L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028296L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028297L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028298L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028299L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028300L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507132127L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507132128L));
        list.add(new AppPackageResource(professionalPackageId, 1517316464697687851L));

        list.add(new AppPackageResource(professionalPackageId, 1517321342507028301L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028302L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028303L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028304L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028305L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028306L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028307L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507132129L));

        appPackageResourceBaseMapper.insertBatchSomeColumn(list);

        // 初始化尊享版 应用套餐资源数据
        list = new ArrayList<>();
        list.add(new AppPackageResource(premiumPackageId, 1496754892604178461L));
        list.add(new AppPackageResource(premiumPackageId, 1496754892604178462L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258921L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258922L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258923L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258924L));
        list.add(new AppPackageResource(premiumPackageId, 1496754892604178459L));
        list.add(new AppPackageResource(premiumPackageId, 1496754892604178460L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258918L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258919L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258920L));
        list.add(new AppPackageResource(premiumPackageId, 1496746245218453164L));


        list.add(new AppPackageResource(premiumPackageId, 1517321342507028292L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028293L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028294L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028295L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028296L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028297L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028298L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028299L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028300L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507132127L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507132128L));
        list.add(new AppPackageResource(premiumPackageId, 1517316464697687851L));

        list.add(new AppPackageResource(premiumPackageId, 1517321342507028301L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028302L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028303L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028304L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028305L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028306L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028307L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507132129L));
        appPackageResourceBaseMapper.insertBatchSomeColumn(list);
    }

    /**
     * 初始化电商套餐资源数据
     *
     * @param basicPackageId 基础版套餐ID
     * @param professionalPackageId 专业版套餐ID
     * @param premiumPackageId 尊享版套餐ID
     */
    private void initBusinessPackageResources(Long basicPackageId, Long professionalPackageId, Long premiumPackageId) {
        // 初始化基础版 应用套餐资源数据
        List<AppPackageResource> list = new ArrayList<>();
        list.add(new AppPackageResource(basicPackageId, 1496754892604178465L));
        list.add(new AppPackageResource(basicPackageId, 1496754892604178466L));
        list.add(new AppPackageResource(basicPackageId, 1504747118353258928L));
        list.add(new AppPackageResource(basicPackageId, 1504747118353258929L));
        list.add(new AppPackageResource(basicPackageId, 1504747118353258930L));
        list.add(new AppPackageResource(basicPackageId, 1504747118353258931L));
        list.add(new AppPackageResource(basicPackageId, 1496754856718452612L));

        list.add(new AppPackageResource(basicPackageId, 1517321342507028285L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507028286L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507028287L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507028288L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507028289L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507028290L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507028291L));
        list.add(new AppPackageResource(basicPackageId, 1517321342507132126L));

        appPackageResourceBaseMapper.insertBatchSomeColumn(list);

        // 初始化专业版 应用套餐资源数据
        list = new ArrayList<>();
        list.add(new AppPackageResource(professionalPackageId, 1496754892604178465L));
        list.add(new AppPackageResource(professionalPackageId, 1496754892604178466L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258928L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258929L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258930L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258931L));
        list.add(new AppPackageResource(professionalPackageId, 1496754892604178463L));
        list.add(new AppPackageResource(professionalPackageId, 1496754892604178464L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258925L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258926L));
        list.add(new AppPackageResource(professionalPackageId, 1504747118353258927L));
        list.add(new AppPackageResource(professionalPackageId, 1496754856718452612L));


        list.add(new AppPackageResource(professionalPackageId, 1517321342507028285L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028286L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028287L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028288L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028289L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028290L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028291L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507132126L));

        list.add(new AppPackageResource(professionalPackageId, 1517321342507028277L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028278L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028279L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028280L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028281L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028282L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028283L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507028284L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507132124L));
        list.add(new AppPackageResource(professionalPackageId, 1517321342507132125L));
        list.add(new AppPackageResource(professionalPackageId, 1517324164641313131L));

        appPackageResourceBaseMapper.insertBatchSomeColumn(list);

        // 初始化尊享版 应用套餐资源数据
        list = new ArrayList<>();
        list.add(new AppPackageResource(premiumPackageId, 1496754892604178465L));
        list.add(new AppPackageResource(premiumPackageId, 1496754892604178466L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258928L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258929L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258930L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258931L));
        list.add(new AppPackageResource(premiumPackageId, 1496754892604178463L));
        list.add(new AppPackageResource(premiumPackageId, 1496754892604178464L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258925L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258926L));
        list.add(new AppPackageResource(premiumPackageId, 1504747118353258927L));
        list.add(new AppPackageResource(premiumPackageId, 1496754856718452612L));

        list.add(new AppPackageResource(premiumPackageId, 1517321342507028285L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028286L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028287L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028288L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028289L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028290L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028291L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507132126L));

        list.add(new AppPackageResource(premiumPackageId, 1517321342507028277L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028278L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028279L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028280L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028281L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028282L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028283L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507028284L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507132124L));
        list.add(new AppPackageResource(premiumPackageId, 1517321342507132125L));
        list.add(new AppPackageResource(premiumPackageId, 1517324164641313131L));

        appPackageResourceBaseMapper.insertBatchSomeColumn(list);
    }

    /**
     * 初始化 口令表（hsl_salt）
     */
    @Transactional(rollbackFor = Exception.class)
    public void initSalt() {
        log.info(">>>>> 初始化 口令表（hsl_work_secret_key）");
        // 平台侧口令
        WorkSecretKey saasWorkSecretKey = new WorkSecretKey();

        saasPwd = EncryptionUtil.createSalt();
        String saasPwdSalt = EncryptionUtil.createSalt();
        String saasPassword = EncryptionUtil.encrypt(saasPwdSalt, saasPwd);

        saasWorkSecretKey.setPassword(saasPassword)
            .setPwdSalt(saasPwdSalt)
            .setTenantCode(databaseConfig.getConnectionInfo().getDbName())
            .setIsCommon(false)
            .setIsRedis(false);
        workSecretKeyBaseMapper.insert(saasWorkSecretKey);

        // redis 口令
        WorkSecretKey redisWorkSecretKey = new WorkSecretKey();

        String redisPwd = EncryptionUtil.createSalt();
        String redisPwdSalt = EncryptionUtil.createSalt();
        String redisPassword = EncryptionUtil.encrypt(redisPwdSalt, redisPwd);

        redisWorkSecretKey.setPassword(redisPassword).setPwdSalt(redisPwdSalt).setIsCommon(false).setIsRedis(true);
        workSecretKeyBaseMapper.insert(redisWorkSecretKey);
    }

    /**
     * 初始化应用共享版口令
     *
     * @param appId 应用ID
     */
    public void initAppSalt(Long appId) {
        WorkSecretKey workSecretKey = new WorkSecretKey();

        String pwd = EncryptionUtil.createSalt();
        String pwdSalt = EncryptionUtil.createSalt();
        String password = EncryptionUtil.encrypt(pwdSalt, pwd);

        workSecretKey.setPassword(password).setPwdSalt(pwdSalt).setAppId(appId).setIsCommon(true).setIsRedis(false);
        workSecretKeyBaseMapper.insert(workSecretKey);
    }

    /**
     * 初始化 IAM账号表（hsl_iam_account）
     *
     * @param saasPwd 平台侧口令
     * @return 记录id
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initIamAccount(String saasPwd) {
        log.info(">>>>> 初始化 IAM账号表（hsl_iam_account）");

        IamAccountInfo iamAccountInfo = new IamAccountInfo();

        iamAccountInfo.setDomainId(iam.getIamDomainId())
            .setDomainName(iam.getIamDomain())
            .setProjectId(iam.getProjectId())
            .setEndpoint(iam.getEndpoint())
            .setIamName(iam.getIamUser())
            .setDescription("用于资源部署")
            .setRegion(iam.getRegion());

        String password = EncryptionUtil.encrypt(saasPwd, iam.getIamPassword());
        String ak = EncryptionUtil.encrypt(saasPwd, iam.getAccessKey());
        String sk = EncryptionUtil.encrypt(saasPwd, iam.getSecretKey());

        iamAccountInfo.setPassword(password).setAk(ak).setSk(sk);

        iamAccountInfoBaseMapper.insert(iamAccountInfo);

        return iamAccountInfo.getId();
    }

    /**
     * 初始化 应用模板表（hsl_app_info）
     *
     * @param saasPwd 平台侧口令
     * @return List of appId
     */
    public List<Long> initAppTemplate(String saasPwd) {
        log.info(">>>>> 初始化 应用模板表（hsl_app_template）");
        List<Long> appIdList = new ArrayList<>(5);

        // 添加 平台侧控制台应用 记录
        Long platformConsoleAppId = initPlatFormConsoleAppTemplate(saasPwd);
        initAppSalt(platformConsoleAppId);
        appIdList.add(0, platformConsoleAppId);

        // 添加 租户侧控制台应用 记录
        Long tenantConsoleAppId = initTenantConsoleAppTemplate(saasPwd);
        initAppSalt(tenantConsoleAppId);
        appIdList.add(1, tenantConsoleAppId);

        // 添加 酒店应用 记录
        Long hotelAppId = initHotelAppTemplate(saasPwd);
        initAppSalt(hotelAppId);
        appIdList.add(2, hotelAppId);

        // 添加 电商应用 记录
        Long businessAppId = initBusinessAppTemplate(saasPwd);
        initAppSalt(businessAppId);
        appIdList.add(3, businessAppId);

        // 添加 微服务架构应用（对应云商店商品） 记录
        if (idaas.getApplicationHttpsMicro().getEnabled()) {
            Long microAppId = initMicroAppTemplate(saasPwd);
            initAppSalt(microAppId);
            appIdList.add(4, microAppId);
        }

        return appIdList;
    }

    /**
     * 添加 平台侧控制台应用 记录
     *
     * @param saasPwd 平台侧口令
     * @return appId
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initPlatFormConsoleAppTemplate(String saasPwd) {
        log.info(">>>>> 添加 平台侧控制台应用 记录");

        OneAccessAppDto platformAppDto = generateOneAccessConsoleAppDto(saasPwd);

        AppTemplate appTemplate = new AppTemplate().setIdaasAppId(platformAppDto.getIdaasAppId())
            .setArchitecture(idaas.getApplicationHttpsConsole().getArchitecture())
            .setIdaasClientSecret(platformAppDto.getIdaasClientSecret())
            .setIdaasClientId(platformAppDto.getIdaasClientId())
            .setName("平台侧" + platformAppDto.getName())
            .setNameEn(platformAppDto.getNameEn())
            .setDomain(platformAppDto.getDomain())
            .setType(AppTypeEnum.SAAS.getLabel())
            .setDescription("平台侧控制台应用")
            .setIfIntegrateThirdApp(false)
            .setIfIntegrateCm(false)
            .setVersion("v1.0");

        appTemplateBaseMapper.insert(appTemplate);

        Long appId = appTemplate.getId();
        if (appId == null || appId == 0L) {
            throw new BizException(ExceptionCode.APPID_ACQUIRE_ERROR);
        }

        log.info("平台侧控制台应用模板id: {}", appId);

        return appId;
    }

    /**
     * 添加 租户侧控制台应用 记录
     *
     * @param saasPwd 平台侧口令
     * @return appId
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initTenantConsoleAppTemplate(String saasPwd) {
        log.info(">>>>> 添加 租户侧控制台应用 记录");

        OneAccessAppDto oneAccessAppDto = generateOneAccessConsoleAppDto(saasPwd);

        AppTemplate appTemplate = new AppTemplate().setIdaasAppId(oneAccessAppDto.getIdaasAppId())
            .setArchitecture(idaas.getApplicationHttpsConsole().getArchitecture())
            .setIdaasClientSecret(oneAccessAppDto.getIdaasClientSecret())
            .setIdaasClientId(oneAccessAppDto.getIdaasClientId())
            .setName("租户侧" + oneAccessAppDto.getName())
            .setNameEn(oneAccessAppDto.getNameEn())
            .setType(AppTypeEnum.TENANT.getLabel())
            .setDomain(oneAccessAppDto.getDomain())
            .setDescription("租户侧控制台应用")
            .setIfIntegrateThirdApp(false)
            .setIfIntegrateCm(false)
            .setVersion("v1.0");

        appTemplateBaseMapper.insert(appTemplate);

        Long appId = appTemplate.getId();
        if (appId == null || appId == 0L) {
            throw new BizException(ExceptionCode.APPID_ACQUIRE_ERROR);
        }

        log.info("租户侧控制台应用模板id: {}", appId);

        return appId;
    }

    /**
     * 添加 业务应用-酒店应用 记录
     *
     * @param saasPwd 平台侧口令
     * @return appId
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initHotelAppTemplate(String saasPwd) {
        log.info(">>>>> 添加 酒店应用 记录");

        OneAccessAppDto hotelAppDto = generateOneAccessHotelAppDto(saasPwd);

        AppTemplate appTemplate = new AppTemplate().setIdaasAppId(hotelAppDto.getIdaasAppId())
            .setArchitecture(idaas.getApplicationHttpsHotel().getArchitecture())
            .setIdaasAppId(idaas.getApplicationHttpsHotel().getAppId())
            .setIdaasClientSecret(hotelAppDto.getIdaasClientSecret())
            .setIdaasClientId(hotelAppDto.getIdaasClientId())
            .setType(AppTypeEnum.BUSINESS.getLabel())
            .setNameEn(hotelAppDto.getNameEn())
            .setDomain(hotelAppDto.getDomain())
            .setName(hotelAppDto.getName())
            .setIfIntegrateThirdApp(false)
            .setDescription("业务应用-酒店")
            .setIfIntegrateCm(false)
            .setVersion("v1.0");

        appTemplateBaseMapper.insert(appTemplate);

        Long appId = appTemplate.getId();
        if (appId == null || appId == 0L) {
            throw new BizException(ExceptionCode.APPID_ACQUIRE_ERROR);
        }

        log.info("业务应用-酒店应用模板id: {}", appId);

        return appId;
    }

    /**
     * 添加 电商应用 记录
     *
     * @param saasPwd 平台侧口令
     * @return appId
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initBusinessAppTemplate(String saasPwd) {
        log.info(">>>>> 添加 电商应用 记录");

        OneAccessAppDto businessAppDto = generateOneAccessBusinessAppDto(saasPwd);

        AppTemplate appTemplate = new AppTemplate().setIdaasAppId(businessAppDto.getIdaasAppId())
            .setArchitecture(idaas.getApplicationHttpsBusiness().getArchitecture())
            .setIdaasAppId(idaas.getApplicationHttpsBusiness().getAppId())
            .setIdaasClientSecret(businessAppDto.getIdaasClientSecret())
            .setIdaasClientId(businessAppDto.getIdaasClientId())
            .setType(AppTypeEnum.BUSINESS.getLabel())
            .setNameEn(businessAppDto.getNameEn())
            .setDomain(businessAppDto.getDomain())
            .setName(businessAppDto.getName())
            .setIfIntegrateThirdApp(false)
            .setDescription("业务应用-电商")
            .setIfIntegrateCm(false)
            .setVersion("v1.0");

        appTemplateBaseMapper.insert(appTemplate);

        Long appId = appTemplate.getId();
        if (appId == null || appId == 0L) {
            throw new BizException(ExceptionCode.APPID_ACQUIRE_ERROR);
        }

        log.info("业务应用-电商应用模板id: {}", appId);

        return appId;
    }

    /**
     * 添加 微服务架构应用 记录
     *
     * @param saasPwd 平台侧口令
     * @return appId
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initMicroAppTemplate(String saasPwd) {
        log.info(">>>>> 添加 微服务架构应用 记录");

        OneAccessAppDto businessAppDto = generateOneAccessMicroAppDto(saasPwd);

        AppTemplate appTemplate = new AppTemplate().setIdaasAppId(businessAppDto.getIdaasAppId())
            .setArchitecture(idaas.getApplicationHttpsMicro().getArchitecture())
            .setIdaasClientSecret(businessAppDto.getIdaasClientSecret())
            .setIdaasClientId(businessAppDto.getIdaasClientId())
            .setType(AppTypeEnum.BUSINESS.getLabel())
            .setNameEn(businessAppDto.getNameEn())
            .setDomain(businessAppDto.getDomain())
            .setDescription("业务应用-微服务架构")
            .setName(businessAppDto.getName())
            .setIfIntegrateThirdApp(false)
            .setIfIntegrateCm(false)
            .setVersion("v1.0");

        Long appId = idaas.getApplicationHttpsMicro().getId();
        if (appId == null || appId == 0L) {
            throw new BizException(ExceptionCode.APPID_ACQUIRE_ERROR);
        }

        appTemplate.setId(appId);
        appTemplateBaseMapper.insert(appTemplate);

        log.info("业务应用-微服务架构应用模板id: {}", appId);
        return appId;
    }

    /**
     * 添加 单体应用（云联） 记录
     *
     * @param saasPwd 平台侧口令
     * @return appId
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initMonoCloudLinkAppTemplate(String saasPwd) {
        log.info(">>>>> 添加 单体应用（云联） 记录");

        OneAccessAppDto businessAppDto = generateOneAccessMonoCloudLinkAppDto(saasPwd);

        AppTemplate appTemplate = new AppTemplate().setIdaasAppId(businessAppDto.getIdaasAppId())
            .setArchitecture(idaas.getApplicationHttpsMonoCloudLink().getArchitecture())
            .setIdaasClientSecret(businessAppDto.getIdaasClientSecret())
            .setIdaasClientId(businessAppDto.getIdaasClientId())
            .setType(AppTypeEnum.BUSINESS.getLabel())
            .setDescription("业务应用-单体应用（云联）")
            .setNameEn(businessAppDto.getNameEn())
            .setDomain(businessAppDto.getDomain())
            .setName(businessAppDto.getName())
            .setIfIntegrateThirdApp(true)
            .setIfIntegrateCm(false)
            .setVersion("v1.0");

        Long appId = idaas.getApplicationHttpsMonoCloudLink().getId();
        if (appId == null || appId == 0L) {
            throw new BizException(ExceptionCode.APPID_ACQUIRE_ERROR);
        }

        appTemplate.setId(appId);
        appTemplateBaseMapper.insert(appTemplate);

        log.info("业务应用-单体应用（云联）模板id: {}", appId);
        return appId;
    }

    /**
     * 生成OneAccess控制台应用基本信息
     *
     * @param saasPwd 平台侧工作秘钥
     * @return OneAccess控制台应用基本信息
     */
    private OneAccessAppDto generateOneAccessConsoleAppDto(String saasPwd) {
        Idaas.IdaasApplicationConsole idaasApplicationConsole = idaas.getApplicationHttpsConsole();

        OneAccessAppDto oneAccessAppDto = new OneAccessAppDto()
            .setIdaasClientSecret(EncryptionUtil.encrypt(saasPwd, idaasApplicationConsole.getClientSecret()))
            .setIdaasClientId(idaasApplicationConsole.getClientId())
            .setIdaasAppId(idaasApplicationConsole.getAppId())
            .setNameEn(idaasApplicationConsole.getNameEn())
            .setName(idaasApplicationConsole.getName());

        if (IdaasEnum.IdaasTypeEnum.ONE_ACCESS.getName().equals(idaas.getType())) {
            oneAccessAppDto.setDomain(idaas.getOneaccess().getDomain());
        }
        return oneAccessAppDto;
    }

    /**
     * 生成OneAccess电商应用基本信息
     *
     * @param saasPwd 平台侧工作秘钥
     * @return OneAccess电商应用基本信息
     */
    private OneAccessAppDto generateOneAccessBusinessAppDto(String saasPwd) {
        Idaas.IdaasApplicationBusiness idaasApplicationBusiness = idaas.getApplicationHttpsBusiness();
        OneAccessAppDto oneAccessAppDto = new OneAccessAppDto()
            .setIdaasClientSecret(EncryptionUtil.encrypt(saasPwd, idaasApplicationBusiness.getClientSecret()))
            .setIdaasClientId(idaasApplicationBusiness.getClientId())
            .setIdaasAppId(idaasApplicationBusiness.getAppId())
            .setNameEn(idaasApplicationBusiness.getNameEn())
            .setName(idaasApplicationBusiness.getName());

        if (IdaasEnum.IdaasTypeEnum.ONE_ACCESS.getName().equals(idaas.getType())) {
            oneAccessAppDto.setDomain(idaas.getOneaccess().getDomain());
        }
        return oneAccessAppDto;
    }

    /**
     * 生成OneAccess酒店应用基本信息
     *
     * @param saasPwd 平台侧工作秘钥
     * @return OneAccess电商应用基本信息
     */
    private OneAccessAppDto generateOneAccessHotelAppDto(String saasPwd) {
        Idaas.IdaasApplicationHotel idaasApplicationHotel = idaas.getApplicationHttpsHotel();

        OneAccessAppDto oneAccessAppDto = new OneAccessAppDto()
            .setIdaasClientSecret(EncryptionUtil.encrypt(saasPwd, idaasApplicationHotel.getClientSecret()))
            .setIdaasClientId(idaasApplicationHotel.getClientId())
            .setIdaasAppId(idaasApplicationHotel.getAppId())
            .setNameEn(idaasApplicationHotel.getNameEn())
            .setName(idaasApplicationHotel.getName());

        if (IdaasEnum.IdaasTypeEnum.ONE_ACCESS.getName().equals(idaas.getType())) {
            oneAccessAppDto.setDomain(idaas.getOneaccess().getDomain());
        }
        return oneAccessAppDto;
    }

    /**
     * 生成OneAccess微服务架构应用基本信息
     *
     * @param saasPwd 平台侧工作秘钥
     * @return OneAccess微服务架构应用基本信息
     */
    private OneAccessAppDto generateOneAccessMicroAppDto(String saasPwd) {
        Idaas.IdaasApplicationMicro idaasApplicationMicro = idaas.getApplicationHttpsMicro();

        OneAccessAppDto oneAccessAppDto = new OneAccessAppDto()
            .setIdaasClientSecret(EncryptionUtil.encrypt(saasPwd, idaasApplicationMicro.getClientSecret()))
            .setIdaasClientId(idaasApplicationMicro.getClientId())
            .setIdaasAppId(idaasApplicationMicro.getAppId())
            .setNameEn(idaasApplicationMicro.getNameEn())
            .setName(idaasApplicationMicro.getName());

        if (IdaasEnum.IdaasTypeEnum.ONE_ACCESS.getName().equals(idaas.getType())) {
            oneAccessAppDto.setDomain(idaas.getOneaccess().getDomain());
        }
        return oneAccessAppDto;
    }

    /**
     * 生成OneAccess单体应用（云联）基本信息
     *
     * @param saasPwd 平台侧工作秘钥
     * @return OneAccess单体应用（云联）基本信息
     */
    private OneAccessAppDto generateOneAccessMonoCloudLinkAppDto(String saasPwd) {
        Idaas.IdaasApplicationMonoCloudLink idaasApplicationMonoCloudLink = idaas.getApplicationHttpsMonoCloudLink();

        OneAccessAppDto oneAccessAppDto = new OneAccessAppDto()
            .setIdaasClientSecret(EncryptionUtil.encrypt(saasPwd, idaasApplicationMonoCloudLink.getClientSecret()))
            .setIdaasClientId(idaasApplicationMonoCloudLink.getClientId())
            .setIdaasAppId(idaasApplicationMonoCloudLink.getAppId())
            .setNameEn(idaasApplicationMonoCloudLink.getNameEn())
            .setName(idaasApplicationMonoCloudLink.getName());

        if (IdaasEnum.IdaasTypeEnum.ONE_ACCESS.getName().equals(idaas.getType())) {
            oneAccessAppDto.setDomain(idaas.getOneaccess().getDomain());
        }
        return oneAccessAppDto;
    }

    /**
     * 生成OneAccess单体应用（License）基本信息
     *
     * @param saasPwd 平台侧工作秘钥
     * @return OneAccess单体应用（License）基本信息
     */
    private OneAccessAppDto generateOneAccessMonoLicenseAppDto(String saasPwd) {
        Idaas.IdaasApplicationMonoLicense idaasApplicationMonoLicense = idaas.getApplicationHttpsMonoLicense();

        OneAccessAppDto oneAccessAppDto = new OneAccessAppDto()
            .setIdaasClientSecret(EncryptionUtil.encrypt(saasPwd, idaasApplicationMonoLicense.getClientSecret()))
            .setIdaasClientId(idaasApplicationMonoLicense.getClientId())
            .setIdaasAppId(idaasApplicationMonoLicense.getAppId())
            .setNameEn(idaasApplicationMonoLicense.getNameEn())
            .setName(idaasApplicationMonoLicense.getName());

        if (IdaasEnum.IdaasTypeEnum.ONE_ACCESS.getName().equals(idaas.getType())) {
            oneAccessAppDto.setDomain(idaas.getOneaccess().getDomain());
        }
        return oneAccessAppDto;
    }

    /**
     * 初始化业务应用API表 （hsl_app_service_api）
     *
     * @param appIdList 业务应用ID列表
     */
    public void initAppServiceApi(List<Long> appIdList) {
        log.info(">>>>> 初始化 业务应用API表（hsl_app_service_api）");

        // 添加 酒店应用 API
        dataRepository.initHotelAppServiceApi(appIdList.get(2));

        // 添加 电商应用 API
        dataRepository.initBusAppServiceApi(appIdList.get(3));

        // 添加 微服务架构应用 API
        if (idaas.getApplicationHttpsMicro().getEnabled()) {
            dataRepository.initMicroAppServiceApi(appIdList.get(4));
        }

    }

    /**
     * 初始化业务应用功能表 （hsl_app_function）
     *
     * @param appIdList 业务应用ID列表
     */
    public void initAppFunctions(List<Long> appIdList) {
        log.info(">>>>> 初始化 业务应用功能表（hsl_app_function）");

        // 添加 酒店应应用 功能
        dataRepository.initHotelAppFunctions(appIdList.get(2));

        // 添加 电商应用 功能
        dataRepository.initBusAppFunctions(appIdList.get(3));

        // 添加 微服务架构应用 功能
        if (idaas.getApplicationHttpsMicro().getEnabled()) {
            dataRepository.initMicroAppFunctions(appIdList.get(4));
        }

    }

    /**
     * 电商应用：初始化 应用角色表（hsl_app_role）+ 应用资源表（hsl_app_resource）+
     * 应用角色资源关系表（hsl_app_role_resource）
     *
     * @param appId 酒店应用 appId
     */
    public void initBusinessRoleResource(Long appId) {
        log.info(">>>>> 电商应用：初始化 应用角色表（hsl_app_role）+ 应用资源表（hsl_app_resource）+ 应用角色资源关系表（hsl_app_role_resource）");

        // 初始化 应用资源表（hsl_app_resource）
        log.info(">>>>> 应用资源表（hsl_app_resource）");
        dataRepository.insertBusinessResource(appId);

        // 初始化 应用角色表（hsl_app_role）
        log.info(">>>>> 应用角色表（hsl_app_role）");
        Long roleId = setBusinessSysAdminSaasLogin(appId).getId();

        // 初始化 应用角色资源关系表（hsl_app_role_resource）
        log.info(">>>>> 应用角色资源关系表（hsl_app_role_resource）");
        List<AppRoleResource> appRoleResourceList = new ArrayList<>();

        // 电商应用资源统计 订单管理
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178463L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178464L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258925L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258926L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258927L, appId));
        // 电商应用资源统计 商品管理
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178465L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178466L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258928L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258929L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258930L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258931L, appId));
        // 电商应用资源统计 退出系统
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754856718452612L, appId));

        appRoleResourceRepository.insertBatchSomeColumn(appRoleResourceList);
    }

    /**
     * 租户侧控制台应用：初始化 应用角色表（hsl_app_role）+ 应用资源表（hsl_app_resource）+
     * 应用角色资源关系表（hsl_app_role_resource）
     *
     * @param appId 租户侧控制台应用 appId
     */
    public void initTenantConsoleRoleResource(Long appId) {
        log.info(">>>>> 租户侧控制台应用 角色资源 数据预置（hsl_app_resource, hsl_app_role, hsl_app_role_resource）");

        log.info(">>>>> 应用资源表 数据预置（hsl_app_resource）");
        dataRepository.insertTenantResource(appId);

        log.info(">>>>> 应用角色表 数据预置（hsl_app_role）");
        AppRole consoleLoginRole = setConsoleLoginRole(appId);
        AppRole defaultLoginRole = setDefaultLoginRole(appId);
        AppRole tenantSysAdminRole = setTenantSysAdminRole(appId, true);

        log.info(">>>>> 应用角色资源关系表 数据预置（hsl_app_role_resource）");
        // 初始化 控制台登录角色 对应资源
        initConsoleLoginRoleResource(consoleLoginRole.getId(), appId);
        // 初始化 默认密码登录角色 对应资源
        initDefaultLoginRoleResource(defaultLoginRole.getId(), appId);
        // 初始化 租户侧系统管理员 对应资源
        initTenantSysAdminRoleResource(tenantSysAdminRole.getId(), appId);
    }

    /**
     * 酒店应用：初始化 应用角色表（hsl_app_role）+ 应用资源表（hsl_app_resource）+
     * 应用角色资源关系表（hsl_app_role_resource）
     *
     * @param appId 酒店应用 appId
     */
    public void initHotelRoleResource(Long appId) {
        log.info(">>>>> 酒店应用：初始化 应用角色表（hsl_app_role）+ 应用资源表（hsl_app_resource）+ 应用角色资源关系表（hsl_app_role_resource）");

        // 初始化 应用资源表（hsl_app_resource）
        log.info(">>>>> 应用资源表（hsl_app_resource）");
        dataRepository.insertHotelResource(appId);

        // 初始化 应用角色表（hsl_app_role）
        Long roleId = setBusinessSysAdminSaasLogin(appId).getId();

        // 初始化 应用角色资源关系表（hsl_app_role_resource）
        log.info(">>>>> 应用角色资源关系表（hsl_app_role_resource）");
        List<AppRoleResource> appRoleResourceList = new ArrayList<>();

        // 酒店应用资源统计 订单管理
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178459L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178460L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258918L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258919L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258920L, appId));
        // 酒店应用资源统计 商品管理
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178461L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178462L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258921L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258922L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258923L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258924L, appId));
        // 酒店应用资源统计 退出系统
        appRoleResourceList.add(new AppRoleResource(roleId, 1496746245218453164L, appId));

        appRoleResourceRepository.insertBatchSomeColumn(appRoleResourceList);
    }

    /**
     * 云商店微服务架构应用：初始化 应用角色表（hsl_app_role）+ 应用资源表（hsl_app_resource）+
     * 应用角色资源关系表（hsl_app_role_resource）
     *
     * @param appId 微服务架构应用 appId
     */
    public void initMicroRoleResource(Long appId) {
        log.info(">>>>> 云商店微服务架构应用：初始化 应用角色表（hsl_app_role）+ 应用资源表（hsl_app_resource）+ 应用角色资源关系表（hsl_app_role_resource）");

        // 初始化 应用资源表（hsl_app_resource）
        log.info(">>>>> 应用资源表（hsl_app_resource）");
        dataRepository.insertMicroResource(appId);

        // 初始化 应用角色表（hsl_app_role）
        log.info(">>>>> 应用角色表（hsl_app_role）");
        Long roleId = setBusinessSysAdminSaasLogin(appId).getId();

        // 初始化 应用角色资源关系表（hsl_app_role_resource）
        log.info(">>>>> 应用角色资源关系表（hsl_app_role_resource）");
        List<AppRoleResource> appRoleResourceList = new ArrayList<>();

        // 微服务架构应用资源统计 订单管理
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178467L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178468L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118356259650L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118356259651L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118356259652L, appId));
        // 微服务架构应用资源统计 商品管理
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178469L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178470L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118356259653L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118356259654L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118356259655L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118356259656L, appId));
        // 微服务架构应用资源统计 退出系统
        appRoleResourceList.add(new AppRoleResource(roleId, 1496746245569441585L, appId));

        appRoleResourceRepository.insertBatchSomeColumn(appRoleResourceList);
    }

    /**
     * 初始化企业默认密码登录角色对应资源
     *
     * @param defaultLoginRoleId 企业登录角色
     * @param appId 应用id
     */
    private void initDefaultLoginRoleResource(Long defaultLoginRoleId, Long appId) {
        List<AppRoleResource> roleResourceList = new ArrayList<>();
        roleResourceList.add(new AppRoleResource(defaultLoginRoleId, 1496754892604178480L, appId));
        roleResourceList.add(new AppRoleResource(defaultLoginRoleId, 1496754892604178481L, appId));
        appRoleResourceRepository.insertBatchSomeColumn(roleResourceList);
    }

    /**
     * 初始化 租户侧系统管理员角色 对应资源
     *
     * @param roleId 租户侧系统管理员角色对应资源
     * @param appId 应用id
     */
    private void initTenantSysAdminRoleResource(Long roleId, Long appId) {
        List<AppRoleResource> appRoleResourceList = new ArrayList<>();

        // 租户侧资源统计 首页
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178449L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178448L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258900L, appId));
        // 租户侧资源统计 组织管理
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178452L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178451L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178450L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258901L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258902L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258903L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258904L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258905L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258906L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258907L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258908L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258909L, appId));
        // 租户侧资源统计 权限管理
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178454L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178453L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258910L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258911L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258912L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258913L, appId));
        // 租户侧资源统计 系统管理
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353449070L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353449071L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178455L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353449072L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258914L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353258915L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118363854300L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118363854301L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118363854302L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118363854303L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118363854304L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118363854305L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118363854306L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118363854307L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118363854308L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118363854309L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118363854310L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118363854311L, appId));
        // 租户侧资源统计 运维中心
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178458L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178456L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178457L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342967465410L, appId));
        // 租户侧资源统计 套餐购买
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604180544L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604180545L, appId));
        // 租户侧资源统计 修改密码
        // 租户侧资源统计 退出系统
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892856946320L, appId));

        appRoleResourceRepository.insertBatchSomeColumn(appRoleResourceList);
    }

    /**
     * 初始化 租户侧控制台登录角色 租户侧控制台应用 应用角色资源关系表（hsl_app_role_resource）
     *
     * @param consoleLoginRoleId 租户侧控制台登录角色 roleId
     * @param appId 租户侧控制台应用 appId
     */
    @Transactional(rollbackFor = Exception.class)
    public void initConsoleLoginRoleResource(Long consoleLoginRoleId, Long appId) {
        List<AppRoleResource> roleResourceList = new ArrayList<>();

        roleResourceList.add(new AppRoleResource(consoleLoginRoleId, 1496754892604178448L, appId));
        roleResourceList.add(new AppRoleResource(consoleLoginRoleId, 1496754892604178449L, appId));
        roleResourceList.add(new AppRoleResource(consoleLoginRoleId, 1504747118353258900L, appId));

        appRoleResourceRepository.insertBatchSomeColumn(roleResourceList);
    }

    /**
     * 平台侧：初始化 角色表（app_role）+ 资源表（app_resource）+ 角色资源关系表（app_role_resource）
     *
     * @param appId 平台侧控制台应用 appId
     */
    @Transactional(rollbackFor = Exception.class)
    public void initPlatformConsoleRoleResource(Long appId) {
        log.info(">>>>> 平台侧：初始化 角色表（app_role）+ 资源表（app_resource）+ 角色资源关系表（app_role_resource）");

        // 初始化 资源表（hsl_resource）
        log.info(">>>>> 资源表（hsl_resource）");
        dataRepository.insertSaasResource(appId);

        // 初始化 角色表（hsl_role）
        log.info(">>>>> 角色表（hsl_role）");
        AppRole paPurchaseRole = setPaPurchaseRole(appId);
        AppRole plSysAdminRole = setPlSysAdminRole(appId);
        setTenantSysAdminRole(appId, false);

        // 初始化 角色资源关系表（hsl_role_resource）
        log.info(">>>>> 角色资源关系表（hsl_role_resource）");
        // 套餐购买角色
        initPaPurchase(paPurchaseRole.getId(), appId);
        // 平台侧系统管理员
        initPlSysAdmin(plSysAdminRole.getId(), appId);
    }

    /**
     * 平台侧：初始化 角色表（role）+ 资源表（resource）+ 角色资源关系表（role_resource）
     *
     * @param platformConsoleAppId 平台侧应用id
     * @param subAppId 平台侧控制台应用
     */
    public void initSelfRoleResource(Long platformConsoleAppId, Long subAppId) {
        log.info(">>>>> 平台侧作为租户 数据初始化：角色表（role）+ 资源表（resource）+ 角色资源关系表（role_resource）");

        List<AppRoleResource> appRoleResources = appRoleResourceRepository.selectList(
            new QueryWrapper<AppRoleResource>().select().eq("is_del", 0).eq("app_id", platformConsoleAppId));

        Map<Long, Long> appResourceIdMap = initResourceData(platformConsoleAppId, subAppId);

        Map<Long, Long> appRoleIdMap = initRoleData(platformConsoleAppId, subAppId, appRoleResources);

        initRoleResourceData(subAppId, appRoleResources, appResourceIdMap, appRoleIdMap);
    }

    private void initRoleResourceData(Long subAppId, List<AppRoleResource> appRoleResources,
        Map<Long, Long> appResourceIdMap, Map<Long, Long> appRoleIdMap) {
        // 初始化 角色资源关系表（hsl_role_resource）
        log.info(">>>>> 角色资源关系表（role_resource）数据预置");
        for (AppRoleResource appRoleResource : appRoleResources) {
            Long resourceId = appResourceIdMap.get(appRoleResource.getResourceId());
            Long roleId = appRoleIdMap.get(appRoleResource.getRoleId());
            roleResourceBaseMapper.insert(new RoleResources(roleId, resourceId, subAppId));
        }
    }

    private Map<Long, Long> initRoleData(Long platformConsoleAppId, Long subAppId,
        List<AppRoleResource> appRoleResources) {
        // 初始化 角色表（hsl_role）
        log.info(">>>>> 角色表（role）数据预置");
        List<AppRole> appRoles = appRoleRepository
            .selectList(new QueryWrapper<AppRole>().eq("app_id", platformConsoleAppId).eq("is_del", 0));

        // 对于有AppRoleResource记录的Role单个插入以获取Role的Id，否则集中插入
        Set<Long> appRoleIds = appRoleResources.stream().map(AppRoleResource::getRoleId).collect(Collectors.toSet());
        List<AppRole> batchInsertAppRoles =
            appRoles.stream().filter(appRole -> !appRoleIds.contains(appRole.getId())).collect(Collectors.toList());
        batchInsertAppRoles.forEach(appRole -> appRole.setId(null));
        List<Role> batchInsertRoles = BeanPlusUtil.toBeanList(batchInsertAppRoles, Role.class);
        batchInsertRoles.forEach(role -> role.setSubAppId(subAppId));
        if (!CollectionUtils.isEmpty(batchInsertRoles)) {
            roleBaseMapper.insertBatchSomeColumn(batchInsertRoles);
        }

        List<AppRole> insertAppRoles =
            appRoles.stream().filter(appRole -> appRoleIds.contains(appRole.getId())).toList();
        Map<Long, Long> appRoleIdMap = new HashMap<>();
        for (AppRole appRole : insertAppRoles) {
            Role role = BeanPlusUtil.toBean(appRole, Role.class);
            role.setSubAppId(subAppId);
            role.setId(null);
            roleBaseMapper.insert(role);
            if (appRoleIds.contains(appRole.getId())) {
                appRoleIdMap.put(appRole.getId(), role.getId());
            }
        }
        return appRoleIdMap;
    }

    private Map<Long, Long> initResourceData(Long appId, Long subAppId) {
        // 初始化 资源表（hsl_resource）
        log.info(">>>>> 资源表（resource）数据预置");
        List<AppResource> appResources =
            appResourceBaseMapper.selectList(new QueryWrapper<AppResource>().eq("app_id", appId).eq("is_del", 0));

        // 对于Resource单个插入，因为要更新ParentId，只能单个插入后获取到每个Resource和App_Resource的对应Id映射关系。
        Map<Long, Long> appResourceIdMap = new HashMap<>();
        for (AppResource appResource : appResources) {
            Resources resources = BeanPlusUtil.toBean(appResource, Resources.class);
            resources.setId(null);
            resources.setSubAppId(subAppId);
            resourceBaseMapper.insert(resources);
            appResourceIdMap.put(appResource.getId(), resources.getId());
        }

        // 获取到appResourceId和resourceId的对应关系后，更新下resource中的parentId
        List<Resources> resourcesList = resourceBaseMapper.selectList(new QueryWrapper<Resources>().eq("is_del", 0));

        resourcesList.forEach(resource -> {
            resource.setParentId(appResourceIdMap.get(resource.getParentId()));
            resourceBaseMapper.updateById(resource);
        });

        return appResourceIdMap;
    }

    /**
     * 初始化 SaaS超级管理员 角色资源关系表（hsl_role_resource）
     *
     * @param roleId SaaS超级管理员 roleId
     * @param subAppId 平台侧控制台应用 appId
     */
    @Transactional(rollbackFor = Exception.class)
    public void initPaPurchase(Long roleId, Long subAppId) {
        log.info(">>>>> 初始化 套餐购买角色 角色资源关系表（app_role_resource）");

        insertPaPurchaseAppRoleResource(roleId, subAppId);
    }

    /**
     * 初始化 SaaS超级管理员 角色资源关系表（hsl_role_resource）
     *
     * @param roleId SaaS超级管理员 roleId
     * @param subAppId 平台侧控制台应用 appId
     */
    @Transactional(rollbackFor = Exception.class)
    public void initPlSysAdmin(Long roleId, Long subAppId) {
        log.info(">>>>> 初始化 平台侧系统管理员 角色资源关系表（app_role_resource）");
        insertAppRoleResource(roleId, subAppId);
    }

    /**
     * 初始化角色资源关系
     *
     * @param roleId 角色ID
     * @param appId 应用ID
     */
    private void insertAppRoleResource(Long roleId, Long appId) {
        List<AppRoleResource> appRoleResourceList = new ArrayList<>();

        // 平台侧资源统计 首页
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178432L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178433L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027300L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027301L, appId));
        // 平台侧资源统计 租户管理中心
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604177070L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604177071L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178434L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178435L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178436L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178437L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178438L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178439L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178440L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178441L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754131341664613L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754131341894613L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754901341664613L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754177341664613L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754131341664453L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027302L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027303L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027304L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027305L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027306L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027307L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027308L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027309L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027310L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027311L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027312L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027313L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027314L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027315L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517324461341634652L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517324461341634653L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517324461341634654L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517322342507027000L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517322342507027001L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517322342507027002L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517322342507027003L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517322342507027004L, appId));
        // 平台侧资源统计 部署中心
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353448961L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353448962L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353456312L, appId));
        // 平台侧资源统计 升级中心
        appRoleResourceList.add(new AppRoleResource(roleId, 1513873475519905792L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1513874390264053760L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1513874390264053761L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1513874390264053762L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1513874390264053763L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1513874390264053764L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1513874390264053765L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1513874390264053766L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027316L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027317L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027318L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027319L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027320L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027321L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027322L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027323L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027324L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027325L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027326L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027327L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027328L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027329L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027330L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027331L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027332L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027333L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321341316416463L, appId));
        // 平台侧资源统计 运维中心
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024418L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024419L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024420L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024421L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024422L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024423L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024424L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024425L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024426L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024427L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024428L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024429L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024430L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024431L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024432L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507025000L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507025001L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507025002L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507025003L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507025004L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027334L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027335L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027336L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027337L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027338L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027339L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027340L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027341L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027342L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027343L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027344L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027345L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027346L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027347L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027348L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027349L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027350L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027351L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027352L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027353L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027354L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027355L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027356L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027357L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027358L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027359L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027360L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027361L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027362L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027363L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027364L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027365L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027366L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027367L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027368L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321378967135623L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321378967135624L, appId));
        // 平台侧资源统计 运营中心
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024433L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024434L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024435L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024436L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024437L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507026000L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507026001L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507026002L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027369L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027370L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027371L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027372L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027373L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027374L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027375L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027376L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027377L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027378L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027379L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027380L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027381L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027382L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027383L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027384L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027385L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027386L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027387L, appId));
        // 平台侧资源统计 计量中心
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024438L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024439L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027000L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027001L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027002L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027388L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027389L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027391L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027392L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027394L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027395L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027396L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027397L, appId));
        // 平台侧资源统计 集成中心
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507021100L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507021101L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507021102L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507021103L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027398L, appId));
        // 平台侧资源统计 系统管理
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178442L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178443L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1504747118353448960L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024409L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024416L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024417L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024441L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024442L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024489L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024487L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507024490L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027399L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027400L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027401L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027402L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027478L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027477L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027403L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027404L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027405L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027406L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027407L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321341234654313L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027408L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027499L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027409L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027410L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027411L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027412L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027413L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027414L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027415L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027416L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027417L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321342507027418L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169840L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169841L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169842L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169844L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169845L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169846L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169999L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169998L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169847L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169888L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169889L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169848L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169849L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169850L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169851L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169852L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169853L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169854L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169855L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169927L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169928L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169929L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169930L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169931L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169932L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169933L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169934L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1517321343585169935L, appId));
        // 平台侧资源统计 退出系统
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892714152531L, appId));

        appRoleResourceBaseMapper.insertBatchSomeColumn(appRoleResourceList);
    }

    /**
     * 初始化角色资源关系
     *
     * @param roleId 角色ID
     * @param appId 应用ID
     */
    private void insertPaPurchaseAppRoleResource(Long roleId, Long appId) {
        List<AppRoleResource> appRoleResourceList = new ArrayList<>();
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178445L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892604178446L, appId));
        appRoleResourceList.add(new AppRoleResource(roleId, 1496754892714152531L, appId));
        appRoleResourceBaseMapper.insertBatchSomeColumn(appRoleResourceList);
    }

    /**
     * 判断能否进行初始化
     * 判断依据：根据 idaas_app_id 查询出的符合条件的记录 等于 0，则可以进行初始化
     *
     * @return true, false
     */
    private Boolean canInit() {
        String consoleId = idaas.getApplicationHttpsConsole().getAppId();
        String businessId = idaas.getApplicationHttpsBusiness().getAppId();
        String hotelId = idaas.getApplicationHttpsHotel().getAppId();

        QueryWrapper<AppTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
            .eq(AppTemplate::getIsDel, 0)
            .in(AppTemplate::getIdaasAppId, consoleId, businessId, hotelId);

        Long count = appTemplateBaseMapper.selectCount(queryWrapper);

        log.info("根据 idaas_app_id 查询出的符合条件的记录数：{}", count);
        return count == 0L;
    }

    /**
     * 初始化单体应用数据
     *
     * @param saasPwd SaaS提供商密钥
     */
    private void initMonoAppData(String saasPwd) {
        boolean monoCloudLink = idaas.getApplicationHttpsMonoCloudLink().getEnabled();
        boolean monoLicense = idaas.getApplicationHttpsMonoLicense().getEnabled();

        if (!monoCloudLink && !monoLicense) {
            log.info("未开启单体应用部署");
            return;
        }

        // 初始化单体应用客户端VPC信息
        Long clientVpcId = initMonoClientVpc();

        // 初始化单体应用客户端安全组信息
        Long clientSecurityGroupId = initMonoClientSecurityGroup();

        // 初始化文件系统安全组信息
        initSfsSecurityGroup();

        if (monoCloudLink) {
            initMonoCloudLinkAppData(saasPwd, clientVpcId, clientSecurityGroupId);
        }

        if (monoLicense) {
            initMonoLicenseAppData(saasPwd, clientVpcId, clientSecurityGroupId);
        }
    }

    /**
     * 初始化单体应用（云联）数据
     *
     * @param saasPwd 平台侧秘钥
     * @param clientVpcId 客户端VPC ID
     * @param clientSecurityGroupId 客户端安全组 ID
     */
    private void initMonoCloudLinkAppData(String saasPwd, Long clientVpcId, Long clientSecurityGroupId) {
        Long monoCloudlinkAppId = initMonoCloudLinkAppTemplate(saasPwd);

        initMonoCloudlinkAppPackage(monoCloudlinkAppId);

        initMonoRole(monoCloudlinkAppId);

        // 初始化单体应用口令
        initAppSalt(monoCloudlinkAppId);

        // 初始化单体应用（云联）部署信息
        initMonoAppDeploymentInfo(monoCloudlinkAppId, clientSecurityGroupId, clientVpcId,
            MonoDeploymentInfoBelongEnum.CLIENT.getBelongTo());
    }

    /**
     * 初始化单体应用（License）数据
     *
     * @param saasPwd 平台侧秘钥
     * @param clientVpcId 客户端VPC ID
     * @param clientSecurityGroupId 客户端安全组 ID
     */
    private void initMonoLicenseAppData(String saasPwd, Long clientVpcId, Long clientSecurityGroupId) {
        Long monoLicenseAppId = initMonoLicenseAppTemplate(saasPwd);

        Long monoLicensePackageId = initMonoLicenseAppPackage(monoLicenseAppId);

        initMonoRole(monoLicenseAppId);

        initAppSalt(monoLicenseAppId);

        Long serverVpcId = initMonoServerVpc();

        initMonoServerSubnet(serverVpcId);

        initMonoLicenseModules(monoLicenseAppId, monoLicensePackageId);

        initMonoAppDeploymentInfo(monoLicenseAppId, clientSecurityGroupId, clientVpcId,
            MonoDeploymentInfoBelongEnum.CLIENT.getBelongTo());

        initMonoAppDeploymentInfo(monoLicenseAppId, null, serverVpcId,
            MonoDeploymentInfoBelongEnum.SERVER.getBelongTo());

        initMonoLicenseModulePackageEcsSpec();
    }

    /**
     * 添加 单体应用（License） 记录
     *
     * @param saasPwd 平台侧口令
     * @return appId
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initMonoLicenseAppTemplate(String saasPwd) {
        log.info(">>>>> 添加 单体应用（License） 记录");

        OneAccessAppDto businessAppDto = generateOneAccessMonoLicenseAppDto(saasPwd);

        AppTemplate appTemplate = new AppTemplate().setIdaasAppId(businessAppDto.getIdaasAppId())
            .setArchitecture(idaas.getApplicationHttpsMonoLicense().getArchitecture())
            .setIdaasClientSecret(businessAppDto.getIdaasClientSecret())
            .setIdaasClientId(businessAppDto.getIdaasClientId())
            .setDescription("业务应用-单体应用（License）")
            .setType(AppTypeEnum.BUSINESS.getLabel())
            .setNameEn(businessAppDto.getNameEn())
            .setDomain(businessAppDto.getDomain())
            .setName(businessAppDto.getName())
            .setIfIntegrateThirdApp(false)
            .setIfIntegrateCm(false)
            .setVersion("v1.0");

        Long appId = idaas.getApplicationHttpsMonoLicense().getId();
        if (appId == null || appId == 0L) {
            throw new BizException(ExceptionCode.APPID_ACQUIRE_ERROR);
        }

        appTemplate.setId(appId);
        appTemplateBaseMapper.insert(appTemplate);

        log.info("业务应用-单体应用（License）模板id: {}", appId);
        return appId;
    }

    /**
     * 初始化单体应用（License）模块信息
     *
     * @param monoLicenseAppId 单体应用（License）模板 ID
     * @param monoLicensePackageId 单体应用套餐 ID
     */
    private void initMonoLicenseModules(Long monoLicenseAppId, Long monoLicensePackageId) {
        // 初始化License应用模块(server_id和security_group_id在调用云服务API创建后再更新至对应记录)
        Long moduleAId = initLicenseAppModule(monoLicenseAppId, idaas.getApplicationHttpsMonoLicense().getModuleAName(),
            idaas.getApplicationHttpsMonoLicense().getModuleAProtocol(),
            idaas.getApplicationHttpsMonoLicense().getModuleAPort());

        Long moduleBId = initLicenseAppModule(monoLicenseAppId, idaas.getApplicationHttpsMonoLicense().getModuleBName(),
            idaas.getApplicationHttpsMonoLicense().getModuleBProtocol(),
            idaas.getApplicationHttpsMonoLicense().getModuleBPort());

        // 初始化License应用套餐及模块关系
        packageModuleBaseMapper.insert(new PackageModule().setPackageId(monoLicensePackageId).setModuleId(moduleAId));
        packageModuleBaseMapper.insert(new PackageModule().setPackageId(monoLicensePackageId).setModuleId(moduleBId));
    }

    /**
     * 初始化单体应用（云联）套餐
     *
     * @param monoCloudlinkAppId 单体应用（云联）应用模板ID
     */
    private void initMonoCloudlinkAppPackage(Long monoCloudlinkAppId) {
        // 初始化套餐表
        AppPackage cloudlinkPackage = new AppPackage();
        cloudlinkPackage.setType(PackageTypeEnum.PROFESSIONAL.getDesc())
            .setEnterpriseSize("中大型")
            .setMultiTenantModel(DbMultiTenantMode.SCHEMA.getMode() + "_" + AppMultiTenantMode.NAMESPACE.getMode())
            .setAppMultiTenantMode(AppMultiTenantMode.NAMESPACE.getMode())
            .setDbMultiTenantMode(DbMultiTenantMode.SCHEMA.getMode())
            .setIfSupportFileSystem(true)
            .setIsExpand(true)
            .setIfSupportLicenseMgmt(false)
            .setAppId(monoCloudlinkAppId)
            .setStatus(true);

        appPackageBaseMapper.insert(cloudlinkPackage);

    }

    /**
     * 初始化单体应用（License）套餐
     *
     * @param monoLicenseAppId 单体应用（License）应用模板ID
     * @return 单体应用（License）套餐ID
     */
    private Long initMonoLicenseAppPackage(Long monoLicenseAppId) {
        // 初始化套餐表
        AppPackage licensePackage = new AppPackage();
        licensePackage.setType(PackageTypeEnum.PROFESSIONAL.getDesc())
            .setEnterpriseSize("中大型")
            .setMultiTenantModel(DbMultiTenantMode.SCHEMA.getMode() + "_" + AppMultiTenantMode.NAMESPACE.getMode())
            .setAppMultiTenantMode(AppMultiTenantMode.NAMESPACE.getMode())
            .setDbMultiTenantMode(DbMultiTenantMode.SCHEMA.getMode())
            .setIfSupportFileSystem(true)
            .setIsExpand(true)
            .setIfSupportLicenseMgmt(true)
            .setAppId(monoLicenseAppId)
            .setStatus(true);

        appPackageBaseMapper.insert(licensePackage);

        return licensePackage.getId();
    }

    /**
     * 云商店单体应用：初始化 应用角色表（hsl_app_role）
     *
     * @param appId 单体应用 appId
     */
    private void initMonoRole(Long appId) {
        log.info(">>>>> 云商店单体应用：初始化 应用角色表（hsl_app_role）");

        // 初始化 应用角色表（hsl_app_role）
        log.info(">>>>> 应用角色表（hsl_app_role）");

        AppRole normal = new AppRole();
        normal.setCode("NORMAL")
            .setName("企业普通用户")
            .setIsBuiltIn(true)
            .setDescription("租户普通用户")
            .setStatus(true)
            .setAppId(appId);
        appRoleRepository.insert(normal);
    }

    /**
     * 初始化License应用模块
     *
     * @param monoLicenseAppId License应用模板ID
     * @param moduleName 模块名称
     * @param protocol 协议
     * @param port 端口号
     * @return 应用模块ID
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initLicenseAppModule(Long monoLicenseAppId, String moduleName, String protocol, Integer port) {

        MonoAppLicenseModule module = new MonoAppLicenseModule();
        module.setAppId(monoLicenseAppId).setName(moduleName).setProtocol(protocol).setPort(port);

        monoAppLicenseModuleBaseMapper.insert(module);

        return module.getId();

    }

    /**
     * 初始化单体应用服务器端VPC信息
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initMonoServerVpc() {
        VpcInfo vpcInfo = new VpcInfo();
        vpcInfo.setVpcUuid(vpc.getServerVpcId())
            .setVpcName(vpc.getServerVpcName())
            .setCidr(vpc.getServerVpcDestination())
            .setSubnetIndex(vpc.getServerVpcSubnetIndex())
            .setBelongTo(VpcBelongEnum.SERVER.getBelongTo())
            .setDescription(VpcBelongEnum.SERVER.getDescription());

        vpcInfoBaseMapper.insert(vpcInfo);

        return vpcInfo.getId();
    }

    /**
     * 初始化单体应用服务器端子网信息
     *
     * @param serverVpcId 单体应用服务器端VPC ID
     * @return 单体应用服务器端子网ID
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initMonoServerSubnet(Long serverVpcId) {
        Subnet subnet = new Subnet();
        subnet.setSubnetUuid(vpc.getLicenseSubnetId())
            .setSubnetName(vpc.getLicenseSubnetName())
            .setVpcId(serverVpcId)
            .setTenantCode(databaseConfig.getConnectionInfo().getDbName())
            .setBelongTo(SubnetBelongEnum.SERVER.getBelongTo())
            .setDescription(SubnetBelongEnum.SERVER.getDescription());

        subnetBaseMapper.insert(subnet);

        return subnet.getId();
    }

    /**
     * 初始化单体应用客户端VPC信息
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initMonoClientVpc() {
        VpcInfo vpcInfo = new VpcInfo();
        vpcInfo.setVpcUuid(vpc.getClientVpcId())
            .setVpcName(vpc.getClientVpcName())
            .setCidr(vpc.getClientVpcDestination())
            .setSubnetIndex(vpc.getClientVpcSubnetIndex())
            .setBelongTo(VpcBelongEnum.CLIENT.getBelongTo())
            .setDescription(VpcBelongEnum.CLIENT.getDescription());

        vpcInfoBaseMapper.insert(vpcInfo);

        return vpcInfo.getId();
    }

    /**
     * 初始化单体应用客户端安全组相关信息
     *
     * @return 安全组记录ID
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initMonoClientSecurityGroup() {
        SecurityGroup securityGroup = new SecurityGroup();

        securityGroup.setSecurityGroupUuid(vpc.getClientSecurityGroupId())
            .setSecurityGroupName(vpc.getClientSecurityGroupName())
            .setIsCreate(true)
            .setBelongTo(SecurityGroupBelongEnum.CLIENT.getBelongTo());

        securityGroupBaseMapper.insert(securityGroup);

        return securityGroup.getId();
    }

    /**
     * 初始化SFS文件系统安全组相关信息
     *
     * @return 安全组记录ID
     */
    @Transactional(rollbackFor = Exception.class)
    public Long initSfsSecurityGroup() {
        SecurityGroup securityGroup = new SecurityGroup();

        securityGroup.setSecurityGroupUuid(vpc.getSfsSecurityGroupId())
            .setSecurityGroupName(vpc.getSfsSecurityGroupName())
            .setIsCreate(true)
            .setBelongTo(SecurityGroupBelongEnum.FILE_SYSTEM.getBelongTo());

        securityGroupBaseMapper.insert(securityGroup);

        return securityGroup.getId();
    }

    /**
     * 初始化单体应用（License）模块服务器规格映射相关信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void initMonoLicenseModulePackageEcsSpec() {

        MonoAppPackageEcsSpec monoAppPackageEcsSpec = new MonoAppPackageEcsSpec();
        monoAppPackageEcsSpec.setAppId(idaas.getApplicationHttpsMonoLicense().getId())
            .setRootVolumeType(ecsSpecification.getModuleRootVolumeType())
            .setRootVolumeSize(ecsSpecification.getModuleRootVolumeSize())
            .setDataVolumeType(ecsSpecification.getModuleDataVolumeType())
            .setDataVolumeSize(ecsSpecification.getModuleDataVolumeSize())
            .setFlavorRef(ecsSpecification.getModuleFlavorRef())
            .setIptype(ecsSpecification.getModuleIpType())
            .setSharetype(ecsSpecification.getModuleShareType())
            .setBandwidthSize(ecsSpecification.getModuleBandWidthSize());

        monoAppPackageEcsSpecBaseMapper.insert(monoAppPackageEcsSpec);

    }

    /**
     * 初始化单体应用部署相关信息
     *
     * @param monoAppId 单体应用模板ID
     * @param securityGroupId 安全组ID
     * @param vpcInfoId 应用VPC ID
     * @param belongTo 部署信息归属
     */
    public void initMonoAppDeploymentInfo(Long monoAppId, Long securityGroupId, Long vpcInfoId, String belongTo) {
        // hsl_iam_account id
        IamAccountInfo iamAccountInfo = iamAccountInfoBaseMapper
            .selectOne(new LambdaQueryWrapper<IamAccountInfo>().eq(IamAccountInfo::getIsDel, 0));

        // hsl_rds_resource id
        RdsResource rdsResource = rdsResourceBaseMapper.selectOne(
            new LambdaQueryWrapper<RdsResource>().eq(RdsResource::getIsDel, 0).eq(RdsResource::getType, "PLATFORM"));

        // hsl_obs_info id
        ObsInfo obsInfo = obsInfoBaseMapper.selectOne(new LambdaQueryWrapper<ObsInfo>().eq(ObsInfo::getIsDel, 0));

        MonoAppDeployment monoAppDeployment = new MonoAppDeployment();
        monoAppDeployment.setAppId(monoAppId)
            .setRegion(iam.getRegion())
            .setProjectId(iam.getProjectId())
            .setEnterpriseProjectId(iam.getEnterpriseProjectId())
            .setIamId(iamAccountInfo.getId())
            .setRdsId(rdsResource.getId())
            .setObsId(obsInfo.getId())
            .setSecurityGroupId(securityGroupId)
            .setVpcId(vpcInfoId)
            .setBelongTo(belongTo);

        monoAppDeploymentBaseMapper.insert(monoAppDeployment);

    }

    /**
     * 初始化云服务SSL认证策略相关信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void initCloudServiceSslStrategy() {
        generateSslStrategy(SSLCloudServiceEnum.CCE, sslStrategy.getCce());
        generateSslStrategy(SSLCloudServiceEnum.LTS, sslStrategy.getLts());
        generateSslStrategy(SSLCloudServiceEnum.CES, sslStrategy.getCes());
        generateSslStrategy(SSLCloudServiceEnum.AOM, sslStrategy.getAom());
        generateSslStrategy(SSLCloudServiceEnum.DCS, sslStrategy.getDcs());
        generateSslStrategy(SSLCloudServiceEnum.RDS, sslStrategy.getRds());
        generateSslStrategy(SSLCloudServiceEnum.IAM, sslStrategy.getIam());
        generateSslStrategy(SSLCloudServiceEnum.SMN, sslStrategy.getSmn());
        generateSslStrategy(SSLCloudServiceEnum.CSE, sslStrategy.getCse());
        generateSslStrategy(SSLCloudServiceEnum.ECS, sslStrategy.getEcs());
        generateSslStrategy(SSLCloudServiceEnum.IMC, sslStrategy.getImc());
        generateSslStrategy(SSLCloudServiceEnum.ELB, sslStrategy.getElb());
        generateSslStrategy(SSLCloudServiceEnum.DNS, sslStrategy.getDns());
        generateSslStrategy(SSLCloudServiceEnum.VPC, sslStrategy.getVpc());
        generateSslStrategy(SSLCloudServiceEnum.WAF, sslStrategy.getWaf());
        generateSslStrategy(SSLCloudServiceEnum.ONEACCESS, sslStrategy.getOneaccess());
        generateSslStrategy(SSLCloudServiceEnum.KEYCLOAK, sslStrategy.getKeycloak());
        generateSslStrategy(SSLCloudServiceEnum.GAUSSDB, sslStrategy.getGaussDb());
        generateSslStrategy(SSLCloudServiceEnum.CDN, sslStrategy.getCdn());
    }

    /**
     * 生成并插入SSL认证策略
     *
     * @param sslCloudServiceEnum 云服务枚举值
     * @param serviceValue 云服务SSL认证策略
     */
    private void generateSslStrategy(SSLCloudServiceEnum sslCloudServiceEnum, int serviceValue) {
        CloudServiceSslStrategy cloudServiceSslStrategy = new CloudServiceSslStrategy();
        cloudServiceSslStrategy.setCloudServiceKey(sslCloudServiceEnum.getServiceNum())
            .setComment(sslCloudServiceEnum.getComment())
            .setSslStrategy(serviceValue);
        cloudServiceSslStrategyBaseMapper.insert(cloudServiceSslStrategy);
    }

    private Role getRoleByName(String roleName) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", 0);
        queryWrapper.eq("name", roleName);
        return roleBaseMapper.selectOne(queryWrapper);
    }

    private long getSubscribedAppId() {
        QueryWrapper<SubscribedApp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_console", 1).eq("is_del", 0);
        SubscribedApp hslSubscribedApp = subscribedAppBaseMapper.selectOne(queryWrapper);
        if (BeanPlusUtil.isEmpty(hslSubscribedApp)) {
            throw new BizException("未在订阅应用信息中找到对应的控制台应用");
        }
        return hslSubscribedApp.getId();
    }

    private CseInfo setCseInfoByType(String saasPwd, String type) {
        CseInfo cseInfo = new CseInfo();
        String password = StrUtil.EMPTY;

        if (ServiceManageFrameTypeEnum.CSE.getName().equals(type)) {

            password = EncryptionUtil.encrypt(saasPwd, cse.getPassword());
            cseInfo.setUsername(cse.getName())
                .setRegisterAddress(cse.getDiscoveryAddress())
                .setConfigAddress(cse.getConfigAddress())
                .setInstanceId(cse.getInstanceId());

        } else if (ServiceManageFrameTypeEnum.NACOS.getName().equals(type)) {
            String server = nacos.getNacosServers().get(0);
            String namespaceId = nacos.getNamespace();

            cseInfo.setNamespaceId(namespaceId)
                .setRegisterAddress(server)
                .setConfigAddress(server)
                .setInstanceId(namespaceId);
        }

        cseInfo.setPassword(password).setType(configDiscoveryFrame).setProjectId("default");
        return cseInfo;
    }

    // 平台侧角色
    private AppRole setPaPurchaseRole(Long appId) {
        AppRole paPurchaseRole = new AppRole();
        paPurchaseRole.setCode(RoleCodeEnum.PACKAGE_PURCHASE.getCode())
            .setName(RoleCodeEnum.PACKAGE_PURCHASE.getName())
            .setIsBuiltIn(true)
            .setDescription(RoleCodeEnum.PACKAGE_PURCHASE.getName())
            .setStatus(true)
            .setAppId(appId);
        appRoleBaseMapper.insert(paPurchaseRole);
        return paPurchaseRole;
    }

    // 平台侧角色
    private AppRole setPlSysAdminRole(Long appId) {
        AppRole plSysAdminRole = new AppRole();
        plSysAdminRole.setCode(RoleCodeEnum.PLATFORM_SYS_ADMIN.getCode())
            .setName(RoleCodeEnum.PLATFORM_SYS_ADMIN.getName())
            .setIsBuiltIn(true)
            .setDescription(RoleCodeEnum.PLATFORM_SYS_ADMIN.getName())
            .setStatus(true)
            .setAppId(appId);
        appRoleBaseMapper.insert(plSysAdminRole);
        return plSysAdminRole;
    }

    // 租户侧角色
    private AppRole setConsoleLoginRole(Long appId) {
        AppRole consoleLoginRole = new AppRole();
        consoleLoginRole.setCode(RoleCodeEnum.CONSOLE_LOGIN.getCode())
            .setName(RoleCodeEnum.CONSOLE_LOGIN.getName())
            .setIsBuiltIn(true)
            .setDescription(RoleCodeEnum.CONSOLE_LOGIN.getName())
            .setStatus(true)
            .setAppId(appId);
        appRoleBaseMapper.insert(consoleLoginRole);
        return consoleLoginRole;
    }

    // 租户侧角色
    private AppRole setDefaultLoginRole(Long appId) {
        AppRole defaultLoginRole = new AppRole();
        defaultLoginRole.setCode(RoleCodeEnum.DEFAULT_LOGIN.getCode())
            .setName(RoleCodeEnum.DEFAULT_LOGIN.getName())
            .setIsBuiltIn(true)
            .setDescription(RoleCodeEnum.DEFAULT_LOGIN.getName())
            .setStatus(true)
            .setAppId(appId);
        appRoleBaseMapper.insert(defaultLoginRole);
        return defaultLoginRole;
    }

    // 租户侧角色
    private AppRole setTenantSysAdminRole(Long appId, Boolean status) {
        AppRole tenantSysAdminRole = new AppRole();
        tenantSysAdminRole.setCode(RoleCodeEnum.TENANT_SYS_ADMIN.getCode())
            .setName(RoleCodeEnum.TENANT_SYS_ADMIN.getName())
            .setIsBuiltIn(true)
            .setDescription(RoleCodeEnum.TENANT_SYS_ADMIN.getName())
            .setStatus(status)
            .setAppId(appId);
        appRoleBaseMapper.insert(tenantSysAdminRole);
        return tenantSysAdminRole;
    }

    // 业务系统管理员
    private AppRole setBusinessSysAdminSaasLogin(Long appId) {
        AppRole businessSysAdminRole = new AppRole();
        businessSysAdminRole.setCode(RoleCodeEnum.BUSINESS_SYS_ADMIN.getCode())
            .setName(RoleCodeEnum.BUSINESS_SYS_ADMIN.getName())
            .setIsBuiltIn(true)
            .setDescription(RoleCodeEnum.BUSINESS_SYS_ADMIN.getName())
            .setStatus(true)
            .setAppId(appId);
        appRoleBaseMapper.insert(businessSysAdminRole);
        return businessSysAdminRole;
    }
}
